首页 > 解决方案 > 将数字四舍五入到 1

问题描述

我要做的是将数字向左舍入到 1。例如,如果一个数字是 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))

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

标签: javascriptmathroundingfloor

解决方案


您可以将 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));


推荐阅读