Borislav Hadzhiev
Wed Oct 27 2021·2 min read
Photo by Myles Tan
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.
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.
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
null
value to the Math.floor
function, it returns 0
.Here is the step-by-step example from the code snippet.
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:
10
and round the result down to the next largest
integer.10
to get the number rounded down to the nearest
10
.