关于浮点数加法的问题

发布于 2024-08-15 08:10:25 字数 261 浏览 2 评论 0原文

float totalAmount = 0;
.
.
.//totalAmount assigned value 1.05 correctly
.
totalAmount  += float.Parse(dataRow["Amt"].ToString()); //where dataRow["Amt"] has value 4.93

我得到的 TotalAmount 答案是 5.97999954 而不是 5.98

为什么会发生这种情况?

float totalAmount = 0;
.
.
.//totalAmount assigned value 1.05 correctly
.
totalAmount  += float.Parse(dataRow["Amt"].ToString()); //where dataRow["Amt"] has value 4.93

The answer I get for totalAmount is 5.97999954 instead of 5.98

Why is this happening?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

凉风有信 2024-08-22 08:10:25

您声明累积之前的 totalAmount 为 1.05。这将给出预期结果:

1.05
4.93 +
------
5.98

您将得到 5.97999954,这基本上是 IEEE 浮点最好表示的答案,这是一种无法精确表达每个十进制数的二进制格式。例如,相当常见的 0.110 具有无限二进制浮点表示 .0001100110011...2

还有一个维基百科链接,为了更好地衡量:http://en.wikipedia.org/wiki/Floating_point #Accuracy_problems ;)

You state that totalAmount is 1.05, before the accumulation. That would give expected results of:

1.05
4.93 +
------
5.98

You are getting 5.97999954, which is basically the answer as best represented by IEEE floating point, which is a binary format that cannot exactly express every decimal number. For instance, the rather common 0.110 has an infinite binary floating point representation .0001100110011...2.

And a Wikipedia link, for good measure: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems ;)

李白 2024-08-22 08:10:25

这是由于 base-10 数字以 base-2 系统。

计算机上的浮点数学总是这样做。如果您知道所需的精度级别,则应该使用适当的十进制表示形式。

This is due to representing base-10 numbers in a base-2 system.

Floating point math on computers always does this. If you know the level of precision you'll need you should use the appropriate decimal representation.

孤檠 2024-08-22 08:10:25

jdmichal 是正确的,但我要补充一点,如果您确实希望它正确相加,您可以使用 Decimal 类型(包括十进制文字)。

jdmichal is correct, but I'll add that, if you actually want this to add up correctly, you could use the Decimal type (including decimal literals).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文