Ivan Prodanov
Ivan Prodanov

Reputation: 35532

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

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"?

Upvotes: 20

Views: 45913

Answers (6)

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);

Upvotes: 19

wlodi54
wlodi54

Reputation: 31

this should work.

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

Upvotes: 3

Richard
Richard

Reputation: 109110

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
}

Upvotes: 9

inazaruk
inazaruk

Reputation: 74790

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);

Upvotes: 34

Timotei
Timotei

Reputation: 1919

Or, you could simply check if the input text is not null, or empty.

Also, be careful, because in some countries, the "." (dot) that separates the float numbers is "," (comma)

Upvotes: 3

ChrisF
ChrisF

Reputation: 137178

I've just tried this and it didn't throw any exceptions at all.

Is your number format using decimal comma rather than decimal point? Have you tried:

var s = "0,0";
var f = float.Parse(s);

Having asked this I've just tried it with the comma expecting to get an exception, but didn't. So this might not be the answer.

Upvotes: 3

Related Questions