2

Why is fvalue1 123456792 after the following line of code has executed?

float fvalue1 = Convert.ToSingle("123456789", CultureInfo.InvariantCulture);

Converting to double works as expected:

double dvalue1 = Convert.ToDouble("123456789", CultureInfo.InvariantCulture);
codelove
  • 1,396
  • 3
  • 17
  • 35

2 Answers2

4

You've just discovered for yourself the reason double type exists - its precision is better then float's.

Check out following on the differences between these types: Difference between decimal, float and double in .NET?

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
3

float doesn't have the required precision to represent 123456789, whereas double does.

dlev
  • 48,024
  • 5
  • 125
  • 132
  • [Are you sure?](http://msdn.microsoft.com/en-us/library/system.single.maxvalue.aspx) – Uwe Keim Mar 31 '11 at 17:54
  • @Uwe I am. Still need to learn to not couch my language with unnecessary qualifiers :) – dlev Mar 31 '11 at 17:55
  • @dlev Can you explain, why the precision is relevant here, since the number contains no decimal places, but just an integer? – Uwe Keim Mar 31 '11 at 18:20
  • 2
    @Uwe: **The number certainly does contain decimal places.** Remember how a float is stored. A float is a binary number 1.0101010101010 multiplied by 2^x for some integer x. A float is a sign bit, an integer representing the exponent, and the digits after the "1." – Eric Lippert Mar 31 '11 at 20:36
  • Thanks, @Eric - I really never got into the storage of floating points and all that epsilon stuff. Have do to some homework, I guess. – Uwe Keim Mar 31 '11 at 20:45
  • 2
    @Uwe: See my series on floating point arithmetic if you want the basics and some fun facts about Benford's Law. http://blogs.msdn.com/b/ericlippert/archive/tags/floating+point+arithmetic/ – Eric Lippert Mar 31 '11 at 22:30