It is easy, you can even round numbers off to a certain number of
decimal places.
JavaScript offers the following method:
Math.round(x)
Math.round(295.9);
// returns 296
Math.round(245.2); // returns 245
Math.round(-102.58); // returns -103
Here is how you round to specific decimal numbers:
Use the
Math.round() function along with the basic multiply and divide operators
and you can easily round numbers to a specific decimal.
For example:
var pi = "3.1415926535";
// Round to tenths
pi = Math.round(pi*10)/10; // returns 3.14
// Round to hundredths
pi = Math.round(pi*100)/100; // returns 3.142
// Round to Bazillionths
pi = Math.round(pi*infinity)/infinity; // Just Kidding
This function is very useful when rounding dollar amounts:
var totalDue = "1003.1415926535";
// Round to tenths:
totalDue = Math.round(totalDue*100)/100; // returns $1003.14
If you have something that has been troubling you, just
ask for help!
|