Round a Number Up to the Nearest 100 in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 27, 2021

banner

Photo from Unsplash

Round a Number Up to the Nearest 100 #

To round a number up to the nearest 100, call the Math.ceil function, passing it the number divided by 100 as a parameter and then multiply the result by 100, e.g. Math.ceil(num / 100) * 100. The Math.ceil function rounds a number up to the next largest integer.

index.js
function roundUpToNearest100(num) { return Math.ceil(num / 100) * 100; } console.log(roundUpToNearest100(101)); // 👉️ 200 console.log(roundUpToNearest100(199)); // 👉️ 200 console.log(roundUpToNearest100(100.001)); // 👉️ 200 console.log(roundUpToNearest100(-399)); // 👉️ -300 console.log(roundUpToNearest100(-301)); // 👉️ -300

If you need to round up or down to the nearest 100, check out my other article - Round a Number (up or down) to the Nearest 100.

If the number we passed to the Math.ceil function has anything after the decimal, the number gets rounded up.

If an integer is passed to the Math.ceil function, it simply returns the number as is.

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

index.js
console.log(Math.ceil(10.01)); // 👉️ 11 console.log(Math.ceil(19.01)); // 👉️ 20 console.log(Math.ceil(20)); // 👉️ 20 console.log(Math.ceil(-10.99)); // 👉️ -10 console.log(Math.ceil(null)); // 👉️ 0
If you pass a null value to the Math.ceil function, it returns 0.

Here are the steps we took to get to the solution.

index.js
console.log(601 / 100); // 👉️ 6.01 console.log(900 / 100); // 👉️ 9 console.log(Math.ceil(601 / 100)); // 👉️ 7 console.log(Math.ceil(900 / 100)); // 👉️ 9 console.log(Math.ceil(601 / 100) * 100); // 👉️ 700 console.log(Math.ceil(900 / 100) * 100); // 👉️ 900

The process consists of 2 steps:

  1. Divide the number by 100 and round the result up to the next largest integer.
  2. Multiply the result by 100 to get the number rounded up 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.