Dart - 减去一些 double 值会产生错误的结果

标签 dart floating-point double floating-accuracy

我选择了两个随机的 double 数字:

double a = 7918.52;
double b = 5000.00;

我希望从 2918.52 获得 a - b
好吧,它给了我 2918.5200000000004 的结果,这看起来很奇怪。
print(a - b); // -> 2918.5200000000004

但是如果我将 double a 更改为 7918.54 ,我将得到 2918.54 的预期结果。

有人可以向我解释为什么某些 double 值会导致意外的舍入问题而其他值不会?

最佳答案

这样做的原因是 floating-point arithmetic 以及 Dart 使用 IEEE 754 standard 的事实就我而言。

所有使用浮点运算的语言都会发生这种情况。您可以通读 similar questions 了解其他编程语言。

General question about floating-point arithmetic 在现代编程语言中。

关于Dart - 减去一些 double 值会产生错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56619416/

相关文章:

dart - 无法加载源 'dart:core/runtime/libobject_patch.dart' : <source not available>

json - 在 Dart 中将现有字符串转换为原始字符串

c++ - 比较 C++ 中的两个 double 没有产生正确的结果

google-app-engine - 将Appengine Channel API与DART结合使用

C# 小数类型相等

algorithm - 如何在 double-double 和 decimal 字符串之间进行转换?

math - float 学运算是否被破坏?

java - java中double 0.0是大于还是小于0

java - 将对象(double 类型)转换为 int

dart - Flutter 相机质量差