Rounding Off Numbers

Math.round()

Using Math.round() rounds of a floating point number to a whole number.

If the number after the point is less than 5 it is rounded to the next lowest number.
If the number after the point is 5 or greater it is rounded to the next highest number


Round off 12.34X to 2 decimal places, where X is a number between 1 and 9

Example numbers

num1=12.444
num2=12.545
num3=12.646

toFixed()

Using toFixed(2) gives 2 results depending on the value of X.
If X is less than 5 it is rounded to the next lowest number.
If X is 5 or greater it is rounded to the next highest number

Results based on my example numbers

Math.ceil()

To ensure X is rounded to the next highest number you can use Math.ceil(num*100)/100

Results based on my example numbers

Math.floor()

To ensure X is rounded to the next lowest number you can use Math.floor(num*100)/100

Results based on my example numbers


Rounding Off Numbers2

Enter a long number 
Enter precision     
Result              

<script type="text/javascript">
<!-- function roundOff(value, precision){ value = "" + value //convert value to string precision = parseInt(precision) var whole = "" + Math.round(value * Math.pow(10, precision)) var decPoint = whole.length - precision if(decPoint != 0) { result = whole.substring(0, decPoint) result += "." result += whole.substring(decPoint, whole.length) } else { result = whole } return result } //--> </script> <form name=myForm> <pre> Enter a long number <input type=text name=text1 value=5.199999999999999999 size=20> Enter precision <input type=text name=text2 value=2 size=2> Result <input type=text name=text3> </pre> <center> <input type=button value=Calculate onClick="myForm.text3.value = roundOff(myForm.text1.value, myForm.text2.value)"> </center> </form>