Round a Number Down to the Nearest 10 in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 27 20212 min read

banner

Photo by Myles Tan

Round a Number Down to the Nearest 10 #

To round a number down to the nearest 10, call the Math.floor() function, passing it the number divided by 10 as a parameter and multiply the result by 10. The Math.floor function returns the largest integer that is less than or equal to the supplied number.

index.js
function roundDownToNearest10(num) { return Math.floor(num / 10) * 10; } console.log(roundDownToNearest10(39)); // ๐Ÿ‘‰๏ธ 30 console.log(roundDownToNearest10(31)); // ๐Ÿ‘‰๏ธ 30 console.log(roundDownToNearest10(399.999)); // ๐Ÿ‘‰๏ธ 390 console.log(roundDownToNearest10(-409)); // ๐Ÿ‘‰๏ธ -410 console.log(roundDownToNearest10(-401)); // ๐Ÿ‘‰๏ธ -410

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.floor function returns a number that represents the largest integer that is less than or equal to the provided number.

In other words, if the passed in number has a fractional part, it gets rounded down to the next integer.

And if the number is an integer, the Math.floor function returns the number as is.

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

index.js
console.log(Math.floor(14.9)); // ๐Ÿ‘‰๏ธ 14 console.log(Math.floor(14.1)); // ๐Ÿ‘‰๏ธ 14 console.log(Math.floor(100)); // ๐Ÿ‘‰๏ธ 100 console.log(Math.floor(-14.9)); // ๐Ÿ‘‰๏ธ -15 console.log(Math.floor(-14.1)); // ๐Ÿ‘‰๏ธ -15 console.log(Math.floor(null)); // ๐Ÿ‘‰๏ธ 0
If you pass a null value to the Math.floor function, it returns 0.

Here is the step-by-step example from the code snippet.

index.js
console.log(39 / 10); // ๐Ÿ‘‰๏ธ 3.9 console.log(70 / 10); // ๐Ÿ‘‰๏ธ 7 console.log(Math.floor(39 / 10)); // ๐Ÿ‘‰๏ธ 3 console.log(Math.floor(70 / 10)); // ๐Ÿ‘‰๏ธ 7 console.log(Math.floor(39 / 10) * 10); // ๐Ÿ‘‰๏ธ 30 console.log(Math.floor(70 / 10) * 10); // ๐Ÿ‘‰๏ธ 70

The process consists of 2 steps:

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