Round a Number to the Next Integer using JavaScript

avatar

Borislav Hadzhiev

Wed Oct 27 20211 min read

Round a Number to the Next Integer #

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
// โœ…๏ธ 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
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
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.

Further Reading #

Join my newsletter

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

Buy Me A Coffee