Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net float to double conversion

Tags:

.net

Can anyone explain why the third output below prints out a value that is 128 from expected value?

I ran 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()));
    }
like image 634
user625895 Avatar asked Feb 21 '11 02:02

user625895


People also ask

Can you convert a float to a double?

The doubleValue() method of Java Float class returns a double value corresponding to this Float Object by widening the primitive values or in simple words by directly converting it to double via doubleValue() method .

Can you convert a double to a float c#?

In C# I can convert doubles to floats by a cast (float) or by Convert. ToSingle() . double x = 3.141592653589793238463; float a = (float)x; float b = Convert. ToSingle(x);

Can we convert object to double in C#?

To convert a specified value to a double-precision floating-point number, use Convert. ToDouble() method. long[] val = { 340, -200}; Now convert it to Double.

What is the difference between float and double?

float and double both have varying capacities when it comes to the number of decimal digits they can hold. float can hold up to 7 decimal digits accurately while double can hold up to 15.


2 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 only have 24 bits of precision. Therefore, when converting to a double, you've lost precision. In this case, it rounded up to 1101 0001 0011 0110 0101 1010 0000 0000.

like image 54
Joel Rondeau Avatar answered Oct 03 '22 08:10

Joel Rondeau


Basically, it is a rounding error.

In the binary representation of a floating point value, the exponent and the mantissa are separated. What this means is that internally, your number is represented as:

(1.634471118450164794921875) * 2^31

However, the first part of that number is restricted to fitting within 23 bits (Wikipedia on 32-bit floats), so we have to round to the nearest 2^-23:

(1.634471118450164794921875) % (0.00000011920928955078125) = 
 1.6344711780548095703125

So your number is actually:

(1.6344711780548095703125) * 2^31

If we evaluate this, we get 3510000128 rather than 3510000000.

In short, this is the same rounding error that you get when you specify 0.1: neither can be expressed exactly given the limitations of the representation.

like image 39
Zooba Avatar answered Oct 03 '22 09:10

Zooba