.Net float before double conversion

Can someone explain why the third result below outputs a value equal to 128 of the expected value?

I executed the following code with Target framework = .NET Framework 4

CODE:

static void Main(string[] args) { float f = 3510000000f; double d = 3510000000d; Console.WriteLine("f = {0:f1}", f); Console.WriteLine("d = {0:f1}", d); Console.WriteLine("f converted to a double = {0:f1}", Convert.ToDouble(f)); Console.WriteLine("f converted to a double using strings = {0:f1}", Convert.ToDouble(f.ToString())); } 
+4
source share
3 answers

3510000000f represented in bits is 1101 0001 0011 0110 0101 1001 1000 0000 . You have a number with 25 bits of precision, and .Net floats have only 24 bits of precision. Therefore, when you convert to double, you have lost accuracy. In this case, it is rounded to 1101 0001 0011 0110 0101 1010 0000 0000 .

+5
source

In principle, this is a rounding error.

In binary representation, floating point values ​​are separated by exponent and mantissa. This means that inside, your number is represented as:

 (1.634471118450164794921875) * 2^31 

However, the first part of this number is limited to setting within 23 bits ( Wikipedia on 32-bit floats ), so we should round to the nearest 2^-23 :

 (1.634471118450164794921875) % (0.00000011920928955078125) = 1.6344711780548095703125 

So your number is actually:

 (1.6344711780548095703125) * 2^31 

If we 3510000128 this, we get 3510000128 , not 3510000000 .

In short, this is the same rounding error that you get when specifying 0.1 : none of them can be accurately expressed given the limitations of the representation.

+3
source

To quote Jon Skeet:

This is not that you actually get extra accuracy - it is that the float did not exactly display the number you were aiming for initially. double is the original swim for sure; toString shows "extra" data that was already present.

Convert float to double without loss of precision

0
source

Source: https://habr.com/ru/post/1340571/


All Articles