Round a Number (up or down) to the Nearest 10 in JS

avatar

Borislav Hadzhiev

Wed Oct 27 20212 min read

banner

Photo by Greg Rakozy

Round a Number to the Nearest 10 #

To round a number to the nearest 10, call the Math.round() function, passing it the number divided by 10 and multiply the result by 10, e.g. Math.round(num / 10) * 10. The Math.round function takes a number, rounds it to the nearest integer and returns the result.

index.js
function roundToNearest10(num) { return Math.round(num / 10) * 10; } console.log(roundToNearest10(24)); // ๐Ÿ‘‰๏ธ 20 console.log(roundToNearest10(25)); // ๐Ÿ‘‰๏ธ 30 console.log(roundToNearest10(54.9)); // ๐Ÿ‘‰๏ธ 50 console.log(roundToNearest10(-26)); // ๐Ÿ‘‰๏ธ -30 console.log(roundToNearest10(-25)); // ๐Ÿ‘‰๏ธ -20

If you only need to round UP to the nearest 10, check out my other article - Round a Number Up to the Nearest 10 in JavaScript.

The Math.round function took care of the heavy lifting for us.

The function rounds a number to the nearest integer.

If the number has a fractional portion of exactly 0.5, the number gets rounded to the next integer in the direction of positive infinity.

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

index.js
console.log(Math.round(9.49)); // ๐Ÿ‘‰๏ธ 9 console.log(Math.round(9.5)); // ๐Ÿ‘‰๏ธ 10 console.log(Math.round(90)); // ๐Ÿ‘‰๏ธ 90 console.log(Math.round(-94.5)); // ๐Ÿ‘‰๏ธ -94 console.log(Math.round(-94.51)); // ๐Ÿ‘‰๏ธ -95 console.log(Math.round(null)); // ๐Ÿ‘‰๏ธ 0
If you invoke the Math.round function with a null value, it returns 0.

Here is the example, covered step-by-step.

index.js
console.log(75 / 10); // ๐Ÿ‘‰๏ธ 7.5 console.log(54 / 10); // ๐Ÿ‘‰๏ธ 5.4 console.log(Math.round(75 / 10)); // ๐Ÿ‘‰๏ธ 8 console.log(Math.round(54 / 10)); // ๐Ÿ‘‰๏ธ 5 console.log(Math.round(75 / 10) * 10); // ๐Ÿ‘‰๏ธ 80 console.log(Math.round(54 / 10) * 10); // ๐Ÿ‘‰๏ธ 50

This is a two step process:

  1. Divide the number by 10 and round the result to the nearest integer.
  2. Multiply the result by 10 to get the number rounded 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