将浮点数转换为双精度,但不能通过ToString [英] Convert float to double loses precision but not via ToString

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

问题描述

我有以下代码:

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

结果相当于:

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

输出

"d1 : 0.300000011920929 ; d2 : 0.300000012 "

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

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