Convert float to double
Solution 1
You could use "decimal" instead of a string.
float f = 5.2F;
decimal dec = new decimal(f);//5.2
double d = (double)dec; //5.2
Solution 2
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.
Single
have a maximum precision of 7 digits, so .NET only shows 7 digits. With a little rounding 5.1999998092651368 is 5.2
toplel32
Updated on July 09, 2022Comments
-
toplel32 almost 2 years
I'm trying to convert
Single
toDouble
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)
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?
-
Patricia Shanahan about 9 years5.1999998092651368 is itself a rounded value. It cannot be exactly represented as a binary fraction. The closest float to 5.2 is 5.19999980926513671875. The closest double to 5.2 is 5.20000000000000017763568394002504646778106689453125