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

avatar

Borislav Hadzhiev

Wed Oct 27 20212 min read

banner

Photo by Henri Pham

Round a Number to the Nearest 100 #

To round a number to the nearest 100, call the Math.round() function, passing it the number divided by 100 and then multiply the result by 100, e.g. Math.round(num / 100) * 100. The Math.round function takes a number, rounds it to the nearest integer and returns the result.

index.js
function roundNearest100(num) { return Math.round(num / 100) * 100; } console.log(roundNearest100(349)); // ๐Ÿ‘‰๏ธ 300 console.log(roundNearest100(350)); // ๐Ÿ‘‰๏ธ 400 console.log(roundNearest100(175.1)); // ๐Ÿ‘‰๏ธ 200 console.log(roundNearest100(-351)); // ๐Ÿ‘‰๏ธ -400 console.log(roundNearest100(-350)); // ๐Ÿ‘‰๏ธ -300

If you only need to round UP to the nearest 100, check out my other article - Round a Number Up to the Nearest 100 in JavaScript.

The main piece of the puzzle is the Math.round function. The function rounds a number to the nearest integer.

If the number has a fractional portion of exactly 0.5, the number gets rounded to the next integer in the direction of positive infinity.

Here are some examples of using the Math.round function.

index.js
console.log(Math.round(6.49)); // ๐Ÿ‘‰๏ธ 6 console.log(Math.round(6.5)); // ๐Ÿ‘‰๏ธ 7 console.log(Math.round(60)); // ๐Ÿ‘‰๏ธ 60 console.log(Math.round(-64.5)); // ๐Ÿ‘‰๏ธ -64 console.log(Math.round(-64.51)); // ๐Ÿ‘‰๏ธ -65 console.log(Math.round(null)); // ๐Ÿ‘‰๏ธ 0
If the Math.round function is called with a null value, it returns 0.

Let's go over the example in a step-by-step manner.

index.js
console.log(250 / 100); // ๐Ÿ‘‰๏ธ 2.5 console.log(440 / 100); // ๐Ÿ‘‰๏ธ 4.4 console.log(Math.round(250 / 100)); // ๐Ÿ‘‰๏ธ 3 console.log(Math.round(440 / 100)); // ๐Ÿ‘‰๏ธ 4 console.log(Math.round(250 / 100) * 100); // ๐Ÿ‘‰๏ธ 300 console.log(Math.round(440 / 100) * 100); // ๐Ÿ‘‰๏ธ 400

The code consists of 2 steps:

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

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