我正在处理浮点数,需要在宽度有限的网页上的小部件上显示它们.我主要使用tofixed(2)表示我的所有浮点数.但是在某些情况下会出现如下数字:0.0000000365468仅0.00因为tofixed(2)而被打印.我不能永久地将它设置为tofixed(8),因为正常情况下会占用太多空间.
在javascript/jquery中是否有任何内置功能,我可以自动将数字四舍五入到最接近的有意义数字(在上面的情况下:0.00000003或者0.00000004说准确)?
您可以获取日志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));Run Code Online (Sandbox Code Playgroud)
一种动态的方法
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));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
353 次 |
| 最近记录: |