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.

BlueSuede
  • 25
  • 2
  • 1
    You cannot "12345.6789, round down to 100000.0000", that is up. Same for "9999999.9999, round down to 1000000.0000". – Yunnosch Mar 24 '20 at 21:05
  • 2
    [`^` is not "to the power of"](https://stackoverflow.com/questions/3618340/javascript-what-does-the-caret-operator-do) – VLAZ Mar 24 '20 at 21:07
  • 2
    Are you aware of what the `^` operator does? Hint, it is not exponential or power. – Yunnosch Mar 24 '20 at 21:08

2 Answers2

0

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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thanks everyone.. I should have been using ** instead of ^. Guess that's one of the many differences between LUA and Javascript. – BlueSuede Mar 24 '20 at 21:27
0

Check this code. It processes characters individually. It seems to do the job.

function rounding(num) {
  const characters = num.toString().split('');
  let replaceWith = '1';
  characters.forEach((character, index) => {
    if (character === '0' || character === '.') {
      return;
    };
    characters[index] = replaceWith;
    replaceWith = '0';
  });
  return characters.join('');
}
console.log(rounding(12345.6789));
console.log(rounding(9999999.9999));
console.log(rounding(0.00456789));
console.log(rounding(5600/100000));
Stratubas
  • 2,939
  • 1
  • 13
  • 18