避免JavaScript奇怪的十进制计算问题 [英] Avoiding problems with JavaScript's weird decimal calculations

查看:168
本文介绍了避免JavaScript奇怪的十进制计算问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚在MDN上阅读了解JS处理数字的一个怪癖对于双精度64位格式IEEE 754值的所有内容,当您执行 .2 + .1 之类的操作时,您将获得 0.30000000000000004 (这就是文章的内容,但我在Firefox中得到 0.29999999999999993 )。因此:

I just read on MDN that one of the quirks of JS's handling of numbers due to everything being "double-precision 64-bit format IEEE 754 values" is that when you do something like .2 + .1 you get 0.30000000000000004 (that's what the article reads, but I get 0.29999999999999993 in Firefox). Therefore:

(.2 + .1) * 10 == 3

评估为 false

这好像很有问题。那么可以做些什么来避免由于JS中不精确的十进制计算引起的错误?

This seems like it would be very problematic. So what can be done to avoid bugs due to the imprecise decimal calculations in JS?

我注意到如果你做 1.2 + 1.1 你得到了正确的答案。那么你应该避免任何涉及小于1的数值的数学吗?因为这似乎非常不切实际。在JS中进行数学运算还有其他危险吗?

I've noticed that if you do 1.2 + 1.1 you get the right answer. So should you just avoid any kind of math that involves values less than 1? Because that seems very impractical. Are there any other dangers to doing math in JS?

编辑:

我明白许多小数部分可以不能存储为二进制文件,但我遇到的大多数其他语言似乎处理错误(如JS处理大于1的数字)似乎更直观,所以我不习惯这个,这就是我想要的原因看看其他程序员如何处理这些计算。


I understand that many decimal fractions can't be stored as binary, but the way most other languages I've encountered appear to deal with the error (like JS handles numbers greater than 1) seems more intuitive, so I'm not used to this, which is why I want to see how other programmers deal with these calculations.

推荐答案

在这些情况下,你会倾向于使用epsilon估计。

In situations like these you would tipically rather make use of an epsilon estimation.

类似(伪代码)

if (abs(((.2 + .1) * 10) - 3) > epsilon)

其中epsilon是什么东西例如0.00000001,或者你需要的任何精度。

where epsilon is something like 0.00000001, or whatever precision you require.

快速阅读比较浮点数

这篇关于避免JavaScript奇怪的十进制计算问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆