Round a Number Up to the Nearest 10 in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 27 20212 min read

banner

Photo by Robin Stuart

Round a Number Up to the Nearest 10 #

To round a number up to the nearest 10, call the Math.ceil() function, passing it the number divided by 10 as a parameter and then multiply the result by 10, e.g. Math.ceil(num / 10) * 10. The Math.ceil function rounds a number up to the next largest integer and returns the result.

index.js
function roundUpNearest10(num) { return Math.ceil(num / 10) * 10; } console.log(roundUpNearest10(71)); // ๐Ÿ‘‰๏ธ 80 console.log(roundUpNearest10(79.9)); // ๐Ÿ‘‰๏ธ 80 console.log(roundUpNearest10(70.01)); // ๐Ÿ‘‰๏ธ 80 console.log(roundUpNearest10(-49)); // ๐Ÿ‘‰๏ธ -40 console.log(roundUpNearest10(-50)); // ๐Ÿ‘‰๏ธ -50

If you need to round up or down to the nearest 10, check out my other article - Round a Number (up or down) to the Nearest 10.

The Math.ceil function handles the heavy lifting for us.

If the passed in number has a fractional part, the Math.ceil function rounds the number up.

If an integer is passed, the function simply returns the number as is.

Here are some examples of using the Math.ceil function.

index.js
console.log(Math.ceil(7.01)); // ๐Ÿ‘‰๏ธ 8 console.log(Math.ceil(71.00001)); // ๐Ÿ‘‰๏ธ 72 console.log(Math.ceil(70)); // ๐Ÿ‘‰๏ธ 70 console.log(Math.ceil(-23.99)); // ๐Ÿ‘‰๏ธ -20 console.log(Math.ceil(null)); // ๐Ÿ‘‰๏ธ 0
If the Math.ceil function is invoked with a null value, it returns 0.

Here is a step-by-step process of the code example.

index.js
console.log(21 / 10); // ๐Ÿ‘‰๏ธ 2.1 console.log(40 / 10); // ๐Ÿ‘‰๏ธ 4 console.log(Math.ceil(21 / 10)); // ๐Ÿ‘‰๏ธ 3 console.log(Math.ceil(40 / 10)); // ๐Ÿ‘‰๏ธ 4 console.log(Math.ceil(21 / 10) * 10); // ๐Ÿ‘‰๏ธ 30 console.log(Math.ceil(40 / 10) * 10); // ๐Ÿ‘‰๏ธ 40

There are 2 steps in the code:

  1. Divide the number by 10 and round the result up to the next largest integer.
  2. Multiply the result by 10 to get the number rounded up to the nearest 10.

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