How to round up to the nearest N in JavaScript


Suppose we have a number,

const num = 76;

However,

  • If we round off this number to nearest 10 place, the result will be 80

  • If we round off this number to nearest 100 place, the result will be 100

  • If we round off this number to nearest 1000 place, the result will be 0

We are required to write a JavaScript function that takes in a number to be rounded as the first argument and the rounding off factor as the second argument.

The function should return the result after rounding off the number.

Example

The code for this will be −

const num = 76;
const roundOffTo = (num, factor = 1) => {
   const quotient = num / factor;
   const res = Math.round(quotient) * factor;
   return res;
};
console.log(roundOffTo(num, 10));
console.log(roundOffTo(num, 100));
console.log(roundOffTo(num, 1000));

And the output in the console will be −

Output

80
100
0

Updated on: 21-Nov-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements