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

查看:26
本文介绍了避免 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天全站免登陆