Rounding numbers with JavascriptRounding numbers with Javascript

Posted May 5th, 2009 in Javascript (Updated February 19th, 2011)

The Javascript Math object has various mathematical functions and constants including .round() for rounding, ceil() for rounding numbers up and floor() for rounding numbers down.

Math.round()

Math.round() will round the number to the nearest integer. There is no parameter for precision so the resulting number will always be an integer. If the decimal part is .5 or higher, the number is rounded up. Here are some examples:

document.write( Math.round(1.4) ); // writes 1
document.write( Math.round(1.5) ); // writes 2

document.write( Math.round(-1.5) ); // writes -1
document.write( Math.round(-1.6) ); // writes -2

Math.floor()

Math.floor() will always round the number down to the nearest integer. As with Math.round() there is no provision for precision so the resulting number is always an integer. Even if the decimal part is .9999 the number will be rounded down. Here are some examples, using the same numbers as above:

document.write( Math.floor(1.4) ); // writes 1
document.write( Math.floor(1.5) ); // writes 1

document.write( Math.floor(-1.5) ); // writes -2
document.write( Math.floor(-1.6) ); // writes -2

Math.ceil()

Math.ceil() will always round the number up (ceil = ceiling). Again there's no precision, so the function only returns integers. And the examples again use the same numbers:

document.write(Math.ceil(1.4)); // writes 2
document.write(Math.ceil(1.5)); // writes 2

document.write(Math.ceil(-1.5)); // writes -1
document.write(Math.ceil(-1.6)); // writes -1

Number.toFixed()

See my fixed number of digits after the decimal place with Javascript post for details about using the toFixed() function.

Related posts:

Comments

blog comments powered by Disqus