将float转换为double [英] Convert float to double

查看:718
本文介绍了将float转换为double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 Single 转换为 Double ,同时保持原始值。我发现以下方法:

I'm trying to convert Single to Double while maintaining the original value. I've found the following method:

Single f = 5.2F;
Double d1 = f; // 5.19999980926514
Double d2 = Double.Parse(f.ToString()); // 5.2 (correct)

这种做法值得推荐吗?我不需要最佳方法,但必须将预期值传递给double。

Is this practice recommendable? I don't need an optimal method, but the intended value must be passed on to the double. Are there even consequences to storing a rounded value in a double?

推荐答案

转换是精确的。所有 Single 值都可以用 Double 值表示,因为它们是用相同的方式构建的,只是具有更多可能的数字。实际上,您看到的 5.2F 5.1999998092651368 。如果您访问 http://www.h-schmidt.net/FloatConverter/IEEE754.html 并插入 5.2 ,您将看到它的指数为 2 ^ 2 (所以 4 ),尾数为 1.2999999523162842 。现在,如果将两个数字相乘,将得到 5.1999998092651368

The conversion is exact. All the Single values can be represented by a Double value, because they are "built" in the same way, just with more possible digits. What you see as 5.2F is in truth 5.1999998092651368. If you go http://www.h-schmidt.net/FloatConverter/IEEE754.html and insert 5.2 you'll see that it has an exponent of 2^2 (so 4) and a mantissa of 1.2999999523162842. Now, if you multiply the two numbers you'll get 5.1999998092651368.

的最大精度为 7位数字,因此.NET仅显示7位数字。稍微舍入 5.1999998092651368 5.2

Single have a maximum precision of 7 digits, so .NET only shows 7 digits. With a little rounding 5.1999998092651368 is 5.2

这篇关于将float转换为double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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