Shmwel
Shmwel

Reputation: 1697

Float TryParse not working as expected from string

I tried several examples/ways of doing it and no expected result.

I store in a string

// Contains in my case "EUR849.00" so I want to get only the proper number.
string properPrice = price[0].Substring(3);

Now, I try to parse this string 849.00into float and I expect to have this format 849,00.

I tried several examples (specific invariant culture, replacing the . with , and then parsing using float.Parse but it doesn't work).

The way I'm doing it is :

float.TryParse(properPrice, NumberStyles.Any, CultureInfo.InvariantCulture, out floatPrice);

The result is 84900.0. Any suggestions? Tx.

Upvotes: 0

Views: 6707

Answers (1)

Mike Hixson
Mike Hixson

Reputation: 5189

You only need specify the culture when parsing when the format of the string is not using the current culture's formatting. So if your culture uses a decimal instead of a comma you don't need to specify it.

If your current culture uses decimals, then you need to specify a culture that uses commas, when you write out the value. In the example below I have picked the German culture, which uses commas.

Also, it looks like you are dealing with currency, so you should decimal instead of float. http://msdn.microsoft.com/en-us/library/364x0z75.aspx

string val = "EUR849.00";
decimal num = Decimal.Parse(val.Substring(3));

string expected = num.ToString(CultureInfo.GetCultureInfo("de-DE"));

Console.WriteLine(expected);

UPDATE With a float:

string val = "EUR849.00";
float num = Single.Parse(val.Substring(3));

string expected = num.ToString("0.00", CultureInfo.GetCultureInfo("de-DE"));

Console.WriteLine(expected);

Upvotes: 1

Related Questions