gpt4 book ai didi

c# - 将 float 转换为 double 会丢失精度但不会通过 ToString

转载 作者:IT王子 更新时间:2023-10-29 04:29:50 31 4
gpt4 key购买 nike

我有以下代码:

float f = 0.3f;
double d1 = System.Convert.ToDouble(f);
double d2 = System.Convert.ToDouble(f.ToString());

结果相当于:

d1 = 0.30000001192092896;
d2 = 0.3;

我很好奇这是为什么?

最佳答案

这不是精度损失 .3 不是 representable in floating point .当系统转换为它四舍五入的字符串时;如果你打印出足够多的有效数字,你会得到更有意义的东西。

看得更清楚

float f = 0.3f;
double d1 = System.Convert.ToDouble(f);
double d2 = System.Convert.ToDouble(f.ToString("G20"));

string s = string.Format("d1 : {0} ; d2 : {1} ", d1, d2);

输出

"d1 : 0.300000011920929 ; d2 : 0.300000012 "

关于c# - 将 float 转换为 double 会丢失精度但不会通过 ToString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5986980/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com