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

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

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 Math.round function does most of the heavy lifting. 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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.