Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
5

Negative 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
-4

To tens or hundreds

Divide, round and multiply back:

console.log(Math.round(1234 / 100) * 100);
console.log(Math.ceil(41 / 10) * 10);

Output:

1200
50

How 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:

5

Common mistake

Math.round() rounds a half up, towards the larger number, even for negative numbers:

console.log(Math.round(-2.5));

Output:

-2

Functions 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.

Thanks for reading!

Donate to the site — we work hard for you.