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

avatar

Borislav Hadzhiev

Wed Oct 27 20211 min read

banner

Photo by Julia Barbosa

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee