转换浮动翻番失去精度,但不通过的ToString [英] Convert float to double loses precision but not via ToString

查看:150
本文介绍了转换浮动翻番失去精度,但不通过的ToString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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



结果等同于:

The results are equivalent to:

d1 = 0.30000001192092896;
d2 = 0.3;



我很好奇,想看看这是为什么?

I'm curious to find out why this is?

推荐答案

它不是精确.3损失不是的表示的浮点。当系统转换为便将串;如果你打印出足够显著的数字,你会得到的东西更有意义。

Its not a loss of precision .3 is not representable in floating point. When the system converts to the string it rounds; if you print out enough significant digits you will get something that makes more sense.

要看得更清楚。

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);



输出

output

"d1 : 0.300000011920929 ; d2 : 0.300000012 "

这篇关于转换浮动翻番失去精度,但不通过的ToString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆