Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

rounding numbers

Status
Not open for further replies.

tinkler

Programmer
Aug 19, 2003
8
US
Is it possible to round numbers to a given number of decimal places in JavaScript? Math:Round() seems to only round to whole numbers. Maybe something similar to a classical 'trim' method would do the trick, but I can't find anything that would do the job....??
 
Here is how I do this type of stuff:
Code:
// round to the nearest tenth

function roundToTenth(numb) {
var ten_x_numb = numb * 10;
var round_numb = Math.round(ten_x_numb) / 10;
return round_numb;
}
 
Here's a more flexible way:

function round(numb, decimalPlaces) {
var multiplier = Math.pow(10, decimalPlaces);
var multipliedNumb = numb * multiplier;
var roundNumb = Math.round(multipliedNumb) / multiplier;
return roundNumb;
}

You can specify how many decimal places, even negative decimal places, which begin to do rounding to the tens, hundreds, etc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top