How to round a number up or down
Short answer
Math.ceil() rounds up, Math.floor() rounds down, Math.round() rounds to the nearest:
console.log(Math.ceil(4.2));
console.log(Math.floor(4.8));
console.log(Math.round(4.5));Output:
5
4
5Negative numbers
For negative numbers down means further from zero. To just drop the fractional part, use Math.trunc():
console.log(Math.floor(-4.2));
console.log(Math.trunc(-4.2));Output:
-5
-4To tens or hundreds
Divide, round and multiply back:
console.log(Math.round(1234 / 100) * 100);
console.log(Math.ceil(41 / 10) * 10);Output:
1200
50How many pages
A typical task for rounding up is the number of pages for a list:
const items = 95;
const perPage = 20;
console.log(Math.ceil(items / perPage));Output:
5Common mistake
Math.round() rounds a half up, towards the larger number, even for negative numbers:
console.log(Math.round(-2.5));Output:
-2Functions used in this recipe
- Math.ceil — Rounds a number up to an integer.
- Math.floor — Rounds a number down to an integer.
- Math.round — Rounds a number to the nearest integer.
- Math.trunc — Drops the fractional part of a number.