0

Possible Duplicate:
.Net float to double conversion

I though I understood floating point but can someone explain the following

float f = 1.85847987E+9F;
double d = Convert.ToDouble(f);

d is now converted to a string as 1858479872.0. I'm assuming the extra 2 is because double cannot represent the floating point number exactly.

My question is why does it seem to be able to rerepsent the same number when assigned directly

double d = 1.85847987E+9;

and it is shown exactly as 185847987.0

Community
  • 1
  • 1
  • 2
    Or because the single precision float could not represent the value. Have a look [here](http://msdn.microsoft.com/en-us/library/b1e65aza(v=VS.100).aspx). – HABO Jan 22 '13 at 14:18
  • 1
    There are plenty of articles here on SO about this - have a rummage. – James Jan 22 '13 at 14:20
  • 2
    Float can store 7 significant digits, you've got 9. A conversion to double cannot magically recover what was lost. – Hans Passant Jan 22 '13 at 14:22

3 Answers3

1

Because double can, and float cannot represent 1.85847987E+9 precisely.

Why the compiler doesn't complains about "float f = 1.85847987E+9F;" if it cant represents it properly

As per C# specification, section 4.1.6 Floating point types

The floating-point operators, including the assignment operators, never produce exceptions.

Tilak
  • 30,108
  • 19
  • 83
  • 131
  • The real question then is: Why the compiler doesn't complains about "`float f = 1.85847987E+9F;`" if it cant represents it properly ! – Nicolas Repiquet Jan 22 '13 at 14:22
  • 1
    @NicolasRepiquet - Properly or exactly? If there is no data type that can represent 1/7 exactly do you just pick a different number? The value is within the range of _float_, so it is acceptable. – HABO Jan 22 '13 at 14:25
  • @Nicolas, This is in line with c# specification. It specifies various rules for exceptional cases. For non exceptional cases with high precision range, Compiler just decreases the precision instead of producing any exception. – Tilak Jan 22 '13 at 14:33
0

The problem is not double but float. Float is limited to 32 bit, while double uses 64 bit for precision.

Gabe
  • 286
  • 1
  • 4
0

Because a float exists out of a sign, mantissa and exponent. See Jon Skeet's answer here how to extract those values.

For 1.85847987E+9F, the mantissa is 7259687 and the exponent is 8. Then mantissa << exponent equals 1858479872. Since the precision for a float is limited to 7 digits, the value of any digit beyond 7 digits depends on the implementation, not the input. You can test this easily by inputting 123456789F.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • If I have a float to start with then what is the most accurate way of converting to a string `code`Convert.ToDouble(1.85847987E+9F).ToString() or 1.85847987E+9F.ToString() – user2000579 Jan 22 '13 at 16:21