Sarah
Sarah

Reputation: 1595

Failed to Parse string to float in C#

I want to convert the following string to "5,28" to float number, I used this code but I got false result. Also I'm setting the device language to french.

Is there something I'm missing? I have tried to convert the string to different culture like CultureInfo("en-US") but still did not work.

bool result = float.TryParse("5,28", NumberStyles.Float,
                             CultureInfo.InvariantCulture.NumberFormat, out number); 

Upvotes: 0

Views: 516

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98750

InvariantCulture uses . as a NumberDecimalSeparator not ,

Since you forced to use Float style, this style includes only AllowDecimalPoint in a separator styles, your method thinks this , is a decimal separator but InvariantCulture does not use it. That's why you get exception.

There are a few things you can do. One option can be Clone an InvariantCulture, set NumberDecimalSeparator property to , and use that cloned culture in your TryParse method.

float f;
var clone = (CultureInfo)CultureInfo.InvariantCulture.Clone();
clone.NumberFormat.NumberDecimalSeparator = ",";
var result = float.TryParse("5,28", NumberStyles.Float, clone, out f); // true

Or you can use a culture that already has , as a NumberDecimalSeparator like tr-TR culture.1

float f;
var result = float.TryParse("5,28", NumberStyles.Float, 
                                    CultureInfo.GetCultureInfo("tr-TR"), out f); // true

1:Since I'm from Turkey :)

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

The reason that the value 5,28 does not parse is that invariant culture uses decimal dot ., not decimal comma.

To solve this problem you could either replace comma with a dot, like this

bool result=float.TryParse(
    "5.28"
,   NumberStyles.Float
,   CultureInfo.InvariantCulture.NumberFormat
,   out number);

or replace CultureInfo.InvariantCulture for a culture that uses comma in place of a dot:

bool result=float.TryParse(
    "6,78"
,   NumberStyles.Float
,   new CultureInfo("de-DE").NumberFormat
,   out number); 

Demo.

Upvotes: 1

Related Questions