Borislav Hadzhiev
Last updated: Oct 27, 2021
Check out my new book
To round a number to the nearest 5, call the Math.round()
function, passing
it the number divided by 5
and multiply the result by 5
. The Math.round
function takes a number, rounds it to the nearest integer and returns the
result.
function roundNearest5(num) { return Math.round(num / 5) * 5; } console.log(roundNearest5(12)); // 👉️ 10 console.log(roundNearest5(13)); // 👉️ 15 console.log(roundNearest5(-13)); // 👉️ -15 console.log(roundNearest5(-12)); // 👉️ -10 console.log(roundNearest5(32.4)); // 👉️ 30 console.log(roundNearest5(32.5)); // 👉️ 35
We used the Math.round function to round a number to the nearest integer.
Here are some examples of using the Math.round
function.
console.log(Math.round(4.49)); // 👉️ 4 console.log(Math.round(4.5)); // 👉️ 5 console.log(Math.round(40)); // 👉️ 40 console.log(Math.round(-44.5)); // 👉️ -44 console.log(Math.round(-44.51)); // 👉️ -45 console.log(Math.round(null)); // 👉️ 0
Math.round
function is invoked with a null
value, it returns 0
.This is how we solved it in a step-by-step manner.
console.log(12 / 5); // 👉️ 2.4 console.log(13 / 5); // 👉️ 2.6 console.log(Math.round(12 / 5)); // 👉️ 2 console.log(Math.round(13 / 5)); // 👉️ 3 console.log(Math.round(12 / 5) * 5); // 👉️ 10 console.log(Math.round(13 / 5) * 5); // 👉️ 15
This is a two step process:
5
and round the result to the nearest integer.5
to get the number rounded to the nearest 5
.The Math.round
function handles all the heavy lifting for us.