Rounding numbers with JavascriptRounding numbers with Javascript

Posted May 5th, 2009 in Javascript (Updated August 11th, 2009)

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. The 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 down (ceil = ceiling). Again there's no precision so the function only return 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:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus