Search code examples
javascriptmathmaxrounding

How to round up number to nearest 100/1000 depending on number, in JavaScript?


I have a number that can be in the 2 digits, like 67, 24, 82, or in the 3 digits, like 556, 955, 865, or 4 digits and so on. How can I round up the number to the nearest n+1 digits depending on the number?

Example:

roundup(87) => 100,
roundup(776) => 1000,
roudnup(2333) => 10000

and so on.


Solution

  • You could take the logarithm of ten and round up the value for getting the value.

    function roundup(v) {
        return Math.pow(10, Math.ceil(Math.log10(v)));
    }
    
    console.log(roundup(87));   //   100
    console.log(roundup(776));  //  1000
    console.log(roundup(2333)); // 10000

    For negative numbers, you might save the sign by taking the result of the check as factor or take a negative one. Then an absolute value is necessary, because logarithm works only with positive numbers.

    function roundup(v) {
        return (v >= 0 || -1) * Math.pow(10, 1 + Math.floor(Math.log10(Math.abs(v))));
    }
    
    console.log(roundup(87));    //    100
    console.log(roundup(-87));   //   -100
    console.log(roundup(776));   //   1000
    console.log(roundup(-776));  //  -1000
    console.log(roundup(2333));  //  10000
    console.log(roundup(-2333)); // -10000