Round a Number Down to the Nearest 10 in JavaScript

Wed Oct 27 20212 min read

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
```Copied!```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
```Copied!```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
```Copied!```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`.