Round a Number (up or down) to the Nearest 5 in JS

avatar

Borislav Hadzhiev

Last updated: Oct 27, 2021

banner

Check out my new book

Round a Number to the Nearest 5 #

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.

index.js
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.

index.js
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
When the Math.round function is invoked with a null value, it returns 0.

This is how we solved it in a step-by-step manner.

index.js
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:

  1. Divide the number by 5 and round the result to the nearest integer.
  2. Multiply the result by 5 to get the number rounded to the nearest 5.

The Math.round function handles all the heavy lifting for us.

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.