简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM