Number rounding in JavaScript

JavaScript helps lay the foundation for rounding off numbers with the following method:
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
I

Want to display $25 in standard currency format? How about PI to finity and not beyond? Formatting numbers to specific decimal points entails still Math.round(), but padded with a little multiplication and division. See if you can identify the magic formula involved, with the below examples:
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
 
In case you haven't picked up on it, the formula to round any number to x decimal points is:
1) Multiple the original number by 10^x (10 to the power of x)
2) Apply Math.round() to the result
3) Divide result by 10^x


0 comments: