Rounding numbers with Javascript

Posted in Javascript -

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


Related posts:


Comments