javascript - 将小数点后零个数可变的浮点数自动舍入到第一个非零位
问题描述
我正在处理浮点数,需要将它们显示在宽度有限的网页上的小部件上。我主要使用 tofixed(2) 作为我所有的浮点数。但是在某些情况下0.0000000365468
,只有这样的数字:0.00
由于 tofixed(2) 会打印出我不能将它永久设置为 tofixed(8) 因为正常情况会占用太多空间。
javascript/jquery 中是否有任何内置功能,我可以自动将数字四舍五入到最接近的有意义的数字(在上述情况下:0.00000003
或者0.00000004
准确地说)?
解决方案
您可以取 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));
推荐阅读
- performance - Go - 在用于负载测试的高性能 http 客户端中,如何阻止/忽略所有 cookie?
- python - 如何使用 python 处理我的研究数据?
- javascript - 如何正确地将仿射变换应用于使用有符号距离函数渲染的场景的顶点
- sql - 如何将我的查询结果显示为字符串的一部分?
- angular - 无法通过 Angular 模板上的 Codelyzer 禁用 tslint 规则
- meta - 什么组织创建或保管 HTML 元标记?
- selenium - windows10上IE11切换窗口时出错
- axon - Axon Token [IndexTrackingToken{globalIndex=2}] 类型错误
- c# - Windows Auth on MVC 5 asks to log in and denies valid user if I add filters
- javascript - Vue将响应数据重定向到vue对象