Borislav Hadzhiev
Wed Oct 27 2021·1 min read
Photo by Jason Strull
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.
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.
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
null
value to the Math.ceil
function, it returns 0
.Here are the steps we took to get to the solution.
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:
100
and round the result up to the next largest
integer.100
to get the number rounded up to the nearest
100
.