Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

float.Parse() doesn't work the way I wanted

Tags:

c#

I have a text file,which I use to input information into my application.The problem is that some values are float and sometimes they are null,which is why I get an exception.

        var s = "0.0";
        var f = float.Parse(s);

The code above throws an exception at line 2 "Input string was not in a correct format."

I believe the solution would be the advanced overloads of float.Parse,which include IFormatProvider as a parameter,but I don't know anything about it yet.

How do I parse "0.0"?

like image 271
Ivan Prodanov Avatar asked Jun 18 '09 18:06

Ivan Prodanov


People also ask

What does float parse do?

The parseFloat() function is used to accept a string and convert it into a floating-point number. If the input string does not contain a numeral value or If the first character of the string is not a number then it returns NaN i.e, not a number.

What does float parse do in C#?

The float. Parse() method is used to convert given string value to the float value.


3 Answers

Dot symbol "." is not used as separator (this depends on Culture settings). So if you want to be absolutely sure that dot is parsed correctly you need to write something like this:

CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
ci.NumberFormat.CurrencyDecimalSeparator = ".";
avarage = double.Parse("0.0",NumberStyles.Any,ci);
like image 166
inazaruk Avatar answered Nov 01 '22 14:11

inazaruk


Following works for me:

string stringVal = "0.0";
float floatVal = float.Parse(stringVal , CultureInfo.InvariantCulture.NumberFormat);

The reverse case (works for all countries):

float floatVal = 0.0f;
string stringVal = floatVal.ToString("F1", new CultureInfo("en-US").NumberFormat);
like image 26
Jens van de Mötter Avatar answered Nov 01 '22 14:11

Jens van de Mötter


You can check for null or empty string first.

You can also use one of the overloads of Parse (or even use TryParse) to give more specific control.

E.g. to check using the invarient culture, to avoid decimal separator variations with non-user visible data (e.g. from A2A communications):

float SafeParse(string input) {
  if (String.IsNullOrEmpty(input)) { throw new ArgumentNullException("input"); }

  float res;
  if (Single.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out res)) {
    return res;
  }

  return 0.0f; // Or perhaps throw your own exception type
}
like image 9
Richard Avatar answered Nov 01 '22 14:11

Richard