Round a Number to the Next Integer using JavaScript

Borislav Hadzhiev

Wed Oct 27 2021ยท1 min read

Photo by Nikolay Hristov

**Use the Math.ceil() function to round a number to the next integer. The
Math.ceil function takes a number as a parameter, rounds the number up to the
next largest integer and returns the result.**

index.js

Copied!`// โ ๏ธ Math.ceil = Always round up to NEXT integer // โ Math.round = round to NEAREST integer console.log(Math.ceil(3.01)); // ๐๏ธ 4 console.log(Math.round(3.01)); // ๐๏ธ 3 console.log(Math.ceil(3.5)); // ๐๏ธ 4 console.log(Math.round(3.5)); // ๐๏ธ 4`

We used the Math.ceil function to round a number to the next integer.

The function returns the smallest integer that is greater than or equal to the provided number.

index.js

Copied!`console.log(Math.ceil(0.1)); // ๐๏ธ 1 console.log(Math.ceil(-1.05)); // ๐๏ธ -1 console.log(Math.ceil(5.0001)); // ๐๏ธ 6 console.log(Math.ceil(-5)); // ๐๏ธ -5`

Note that negative numbers also get rounded to the next greater or equal integer.

In short, if there is anything after the decimal, the number will get rounded to the next integer, otherwise the number is returned.

This is very different from the Math.round function, which rounds to the nearest integer.

index.js

Copied!`console.log(Math.round(0.49)); // ๐๏ธ 1 console.log(Math.round(0.5)); // ๐๏ธ 1`

If the number is positive and its fractional part is greater than or equal to
`0.5`

, it gets rounded to the next higher absolute value.

If the number is positive and its fractional portion is less than `0.5`

, it gets
rounded to the lower absolute value.

I'll send you 1 email a week with links to all of the articles I've written that week