Converting String To Float in C#

Mehmet picture Mehmet · Jun 26, 2012 · Viewed 520.3k times · Source

I am converting a string like "41.00027357629127", and I am using;

Convert.ToSingle("41.00027357629127");

or

float.Parse("41.00027357629127");

These methods return 4.10002732E+15.

When I convert to float I want "41.00027357629127". This string should be the same...

Answer

Matthew Watson picture Matthew Watson · Jun 26, 2012

Your thread's locale is set to one in which the decimal mark is "," instead of ".".

Try using this:

float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);

Note, however, that a float cannot hold that many digits of precision. You would have to use double or Decimal to do so.