有没有办法在 Javascript 中截断科学记数法数字?
众所周知,因为它是 SO 上最受关注的主题之一,所以我遇到了舍入错误的问题(这实际上不是错误,我很清楚)。 我不会解释我的观点,而是举例说明我可能拥有哪些数字以及我希望能够获得哪些输入:
假设
var a = 15 * 1e-9;
alert(a)
输出
1.5000000000000002e-8
我希望能够获得1.5e-8
相反,但我不能只乘以 10e8,四舍五入并除以 10e8,因为我不知道它是 e-8 还是 e-45 或者其他什么。
所以基本上我希望能够获得 1.5000002
部分,应用 toFixed(3)
并放回指数部分。
我可以转换为字符串并解析,但它看起来不太正确......
有什么想法吗?
(如果您觉得这是许多重复问题之一,我提前道歉,但我找不到类似的问题,只有相关的问题)
Gael
As you all know since it is one of the most asked topic on SO, I am having problems with rounding errors (it isn't actually errors, I am well aware).
Instead of explaining my point, I'll give an example of what possible numbers I have and which input I want to be able to obtain:
Let's say
var a = 15 * 1e-9;
alert(a)
outputs
1.5000000000000002e-8
I want to be able to obtain 1.5e-8
instead, but I cannot just multiply by 10e8, round and divide by 10e8 because I don't know if it will be e-8 or e-45 or anything else.
So basically I want to be able to obtain the 1.5000002
part, apply toFixed(3)
and put back the exponent part.
I could convert into a string and parse but it just doesn't seem right...
Any idea ?
(I apologize in advance if you feel this is one of many duplicates, but I could not find a similar question, only related ones)
Gael
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
toPrecision
方法:You can use the
toPrecision
method:如果您正在进行科学研究并且需要考虑有效数字的舍入:四舍五入到任意数量的有效数字
If you're doing scientific work and need to round with significant figures in mind: Rounding to an arbitrary number of significant digits