首页 > 解决方案 > 将小数点后零个数可变的浮点数自动舍入到第一个非零位

问题描述

我正在处理浮点数,需要将它们显示在宽度有限的网页上的小部件上。我主要使用 tofixed(2) 作为我所有的浮点数。但是在某些情况下0.0000000365468,只有这样的数字:0.00由于 tofixed(2) 会打印出我不能将它永久设置为 tofixed(8) 因为正常情况会占用太多空间。

javascript/jquery 中是否有任何内置功能,我可以自动将数字四舍五入到最接近的有意义的数字(在上述情况下:0.00000003或者0.00000004准确地说)?

标签: javascriptjquery

解决方案


您可以取 log 10并使用阈值来取值。

function f(x) {
    return x.toFixed(Math.log10(x) < -2 ? 8 : 2);
}

console.log(f(0.0000000365468));
console.log(f(0.000000365468));
console.log(f(0.00000365468));
console.log(f(0.0000365468));
console.log(f(0.000365468));
console.log(f(0.00365468));
console.log(f(0.0365468));
console.log(f(12.34));

动态方法

function f(x) {
    return x.toFixed(Math.max(-Math.log10(x) + 1, 2));
}

console.log(f(0.0000000365468));
console.log(f(0.000000365468));
console.log(f(0.00000365468));
console.log(f(0.0000365468));
console.log(f(0.000365468));
console.log(f(0.00365468));
console.log(f(0.0365468));
console.log(f(12.34));


推荐阅读