Round a Number Up to the Nearest 10 in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 24, 2022

banner

Photo from Unsplash

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 rounding a number to the nearest 10.

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.