向下舍入到1的整数

问题描述 投票:1回答:2

[我想做的是将数字从左向下四舍五入。例如,如果一个数字为12345.6789,则四舍五入为100000.0000。如果该数字为9999999.9999,则四舍五入为1000000.0000。还希望它与小数一起使用,因此,如果数字为0.00456789,请将其四舍五入为0.00100000。

在此示例中,5600/100000 = 0.056,我希望将其舍入为0.01。我在LUA脚本中使用以下代码,它可以完美运行。

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

但是如果我对Javascript使用相同的代码,它将返回-11,而不是0.01。

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

任何帮助或指导将不胜感激。

javascript math rounding floor
2个回答
0
投票

您可以floor log 10值,并以10为底的取回指数值。

无法保存带有零的小数位。

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));

0
投票

检查此代码。它单独处理字符。似乎可以完成工作。

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));
© www.soinside.com 2019 - 2024. All rights reserved.