关于浮点数加法的问题
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您声明累积之前的
totalAmount
为 1.05。这将给出预期结果:您将得到 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: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 ;)
这是由于 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.
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).