Converting String To Float in C#

585,813

Solution 1

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.

Solution 2

First, it is just a presentation of the float number you see in the debugger. The real value is approximately exact (as much as it's possible).

Note: Use always CultureInfo information when dealing with floating point numbers versus strings.

float.Parse("41.00027357629127",
      System.Globalization.CultureInfo.InvariantCulture);

This is just an example; choose an appropriate culture for your case.

Solution 3

You can use the following:

float asd = (float) Convert.ToDouble("41.00027357629127");

Solution 4

Use Convert.ToDouble("41.00027357629127");

Convert.ToDouble documentation

Solution 5

The precision of float is 7 digits. If you want to keep the whole lot, you need to use the double type that keeps 15-16 digits. Regarding formatting, look at a post about formatting doubles. And you need to worry about decimal separators in C#.

Share:
585,813
Mehmet
Author by

Mehmet

By Day : I'm developing on a CRM project for Company. By Night : I read articles about new technologies. I play chess and watch football

Updated on October 07, 2020

Comments

  • Mehmet
    Mehmet over 3 years

    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...

  • O. R. Mapper
    O. R. Mapper almost 12 years
    I don't think he's asking how to round it.
  • Mehmet
    Mehmet almost 12 years
    ı tired double.Parse it returns 4100027357629127.0 it is too bad
  • jpe
    jpe almost 12 years
    This sounds like the '.' character is not the decimal separator in your locale? Check out stackoverflow.com/questions/3870154/c-sharp-decimal-separato‌​r
  • Mehmet
    Mehmet almost 12 years
    how can ı choose my CultureInfo ? I am in turkey where ı will add TR-TR ?
  • sshow
    sshow almost 12 years
    @Mehmet new System.Globalization.CultureInfo("tr-TR")
  • Mobiletainment
    Mobiletainment over 10 years
    don't forget to add the namespace using System.Globalization; to access CultureInfo
  • Bas Peeters
    Bas Peeters over 9 years
    Please provide some context as to why this is the right answer.
  • Fran Martinez
    Fran Martinez over 6 years
    Doesn't this change the datatype from float to double? OP wanted float.
  • Sedat Kumcu
    Sedat Kumcu over 3 years
    Thanks for this tip. Works fine