gpt4 book ai didi

Javascript - 将 float 四舍五入到最接近的非零数字的最有效方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:48:00 26 4
gpt4 key购买 nike

我想用(至少)2 位有效数字对 Javascript 中的 float 进行四舍五入。

例如,具有以下预期结果:

roundOff(0.000000001124)  // 0.0000000011 or 1.1e-9 (both acceptable)
roundOff(1.423421) // 1.42
roundOff(0.00053245) // 0.00053
roundOff(422.243224) // 422.24
roundOff(422.0000000123) // 422.00

我知道我可以使用对数和舍入来做与提到的类似的事情 here ,但它会四舍五入更大的数字,例如 -123.0 -> -100

有什么聪明的基于 Javascript 的解决方案吗?

最佳答案

如果我没理解错的话,你想要一个函数,它为绝对值小于 1 的数字返回两位有效数字,或者为绝对值大于 1 的数字返回两位小数。

我仍然不明白为什么您认为 0.000000001124 应该四舍五入为 0.0000000012。您的意思是改写 0.0000000011 吗?

如果是这样,这个函数应该做你想做的:

function roundOff(n) {
return parseFloat(n.toExponential(Math.max(1,2+Math.log10(Math.abs(n)))));
}

例子:

var a = new Array(0.000000001124, 1.423421, 0.00053245, 422.243224,
422.0000000123, 123, -123);
for (i=0; i<7; i++) console.log(roundOff(a[i]));

输出:

1.1e-9
1.42
0.00053
422.24
422
123
-123

关于Javascript - 将 float 四舍五入到最接近的非零数字的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40842250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com