|
Javascript
helps lay the foundation for rounding off numbers with the following
method:
Math.round
(x)
Using this
expression, any supplied argument is rounded off to the nearest integer
by utilizing the ".5" up rule:
Math.round(25.9)
//returns 26
Math.round(25.2) //returns 25
Math.round(-2.58) //returns -3
Let us say
you would like to display $25 in standard currency format or PI to
infinity. Formatting numbers to specific decimal points utilizes
Math.round(), but padded with a little multiplication and division:
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
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
|