Converting String To Float in C#
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#.
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, 2020Comments
-
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 almost 12 yearsI don't think he's asking how to round it.
-
Mehmet almost 12 yearsı tired double.Parse it returns 4100027357629127.0 it is too bad
-
jpe almost 12 yearsThis sounds like the '.' character is not the decimal separator in your locale? Check out stackoverflow.com/questions/3870154/c-sharp-decimal-separator
-
Mehmet almost 12 yearshow can ı choose my CultureInfo ? I am in turkey where ı will add TR-TR ?
-
sshow almost 12 years@Mehmet
new System.Globalization.CultureInfo("tr-TR")
-
Mobiletainment over 10 yearsdon't forget to add the namespace
using System.Globalization;
to accessCultureInfo
-
Bas Peeters over 9 yearsPlease provide some context as to why this is the right answer.
-
Fran Martinez over 6 yearsDoesn't this change the datatype from float to double? OP wanted float.
-
Sedat Kumcu over 3 yearsThanks for this tip. Works fine