Converting String To Float in C#

C#.NetStringFloating PointType Conversion

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

You can use the following:

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

Solution 4 - C#

Use Convert.ToDouble("41.00027357629127");

Convert.ToDouble documentation

Solution 5 - C#

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

Solution 6 - C#

You can double.Parse("41.00027357629127");

Solution 7 - C#

You can use parsing with double instead of float to get more precision value.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMehmetView Question on Stackoverflow
Solution 1 - C#Matthew WatsonView Answer on Stackoverflow
Solution 2 - C#TigranView Answer on Stackoverflow
Solution 3 - C#user4292249View Answer on Stackoverflow
Solution 4 - C#Ozgur DogusView Answer on Stackoverflow
Solution 5 - C#jpeView Answer on Stackoverflow
Solution 6 - C#ABHView Answer on Stackoverflow
Solution 7 - C#LearnerView Answer on Stackoverflow