Monthly Archives: June 2014

Javascript Rounding , turncate , Precision , Formatting

We have got few things to understand

1- Rounding

2- Truncate

3- Precision

4- Formatting


In Javascript Math.round(x) Using it, any supplied argument is rounded off to the nearest integer, and using the “.5” up rule. For example:

Math.round(25.9) //returns 26
Math.round(25.2) //returns 25
Math.round(-2.58) //returns -3

Rounding With Specific Decimal Points

Now For Rounding to specific decimal points

var original=28.453
1) //round "original" to two decimals
var result=Math.round(original*100)/100  //returns 28.45
2) // round "original" to 1 decimal
var result=Math.round(original*10)/10  //returns 28.5
3) //round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000  //returns 8.111

Hence the formula to round any number to x decimal points is:

  • Multiple the original number by 10^x (10 to the power of x)
  • Apply Math.round() to the result
  • Divide result by 10^x