c# string to float conversion invalid?

var x = dr["NationalTotal"].ToString();

gives me 333333333

var xxx = Convert.ToSingle(dr["NationalTotal"].ToString());

gives me 333333344

Any ideas why?

Jon Skeet
people
quotationmark

From the docs for System.Single:

All floating-point numbers have a limited number of significant digits, which also determines how accurately a floating-point value approximates a real number. A Double value has up to 7 decimal digits of precision, although a maximum of 9 digits is maintained internally.

It actually means Single here rather than Double, but the point is that you're trying to use it for 9 significant digits, and that's not guaranteed to be available. You can see this very easily without any parsing:

float f = 333333333f;
Console.WriteLine("{0:r", f); // Prints 333333344

("r" is the "round-trip" format specifier.)

In other words, the closest float value to the exact decimal value of 333333333 is 333333344.

If you were to use Double instead, that would probably retain all the digits, but that doesn't mean it's the right approach necessarily. It depends on the value. Is it actually always an integer? Maybe you should be using long. Is it a non-integer, but financial data (or some other "artificial" value)? If so, consider using decimal.

Also, why are you having to convert this to a string and parse it? What's the execution time type of dr["NationalTotal"]? You may be able to just cast - avoid using string conversions where you don't need to.

people

See more on this question at Stackoverflow