Borislav Hadzhiev
Last updated: Jul 24, 2022
Check out my new book
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.
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.
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.
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
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.
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:
10
and round the result up to the next largest
integer.10
to get the number rounded up to the nearest 10
.