将数字四舍五入到1

时间:2020-03-24 21:02:00

标签: javascript math rounding floor

我要执行的操作是将数字从左向下四舍五入。例如,如果数字为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))

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

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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));