Search code examples
javascriptmathroundingfloor

Rounding numbers down to 1


What I'm trying to do is round the number to the left down to 1. For instance, if a number is 12345.6789, round down to 100000.0000.. If the number is 9999999.9999, round down to 1000000.0000. Also want this to work with decimals, so if a number is 0.00456789, round it down to 0.00100000.

In this example, 5600/100000 = 0.056 and I want it to round to 0.01. I use the following code in LUA scripts and it works perfectly.

function rounding(num)
  return 10 ^ math.floor((math.log(num))/(math.log(10)))
end
print(rounding(5600/100000))

But if I use the same for Javascript, it returns -11, instead of 0.01.

function rounding(num) {
  return 10 ^ Math.round((Math.log(num))/(Math.log(10)))
}
console.log((rounding(5600/100000)).toFixed(8))

Any help or guidance would be greatly appreciated.


Solution

  • You could floor the log10 value and get the value back of the exponential value with the base of 10.

    The decimal places with zeroes can not be saved.

    const format = number => 10 ** Math.floor(Math.log10(number));
    
    var array = [
              12345.6789,     //  100000.0000 this value as a zero to much ...
            9999999.9999,     // 1000000.0000
                  0.00456789, //       0.00100000
        ];
    
    console.log(array.map(format));