【发布时间】:2018-12-07 05:13:21
【问题描述】:
我有以下代码
double temp3 = 61.01;
//This can actually be various other types, but float is the one that causes problems
dynamic temp = 61.01f;
double temp2 = (double)Convert.ChangeType(temp, typeof(double));
double newValue = temp2 - temp3;
//newValue should == 0 but it does not
Console.WriteLine(String.Format(" {0:F20}", temp));
Console.WriteLine(String.Format(" {0:F20}", temp2));
Console.WriteLine(String.Format(" {0:F20}", temp3));
Console.WriteLine(String.Format(" {0:F20}", newValue));
哪个产生
61.01000000000000000000
61.00999832153320000000
61.01000000000000000000
-0.00000167846679488548
为什么 Convert.ChangeType 会丢失精度?
我们使用 Convert.ChangeType 是因为使用了一个动态变量,它可以是 byte/uint/float/double 等
【问题讨论】:
-
我相当肯定答案仍将与this post 相同。您的源数据类型为
float,而.01无法用二进制准确表示:111101.000000101000111101(conversion source)。 -
顺便把格式改成
G20,而不是F20。 -
我现在明白了。 F20是我的问题,通过使用G20我可以看到真正的价值。
-
@John:除了源文本的格式和转换之外,这个问题似乎没有任何浮点算术错误。这个问题似乎是微软格式化的结果,而不是浮点的性质。请不要随意关闭浮点问题作为that question 的重复项,因为这会妨碍人们获得正确答案。
-
@LasseVågsætherKarlsen:除了源文本的格式和转换之外,这个问题似乎没有任何浮点算术错误。这个问题似乎是微软格式化的结果,而不是浮点的性质。请不要随意关闭浮点问题作为that question 的重复项,因为这会妨碍人们获得正确答案。
标签: c# types casting floating-point