0

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

So the solution to OP's question is "replace the ',' in your string with a '.'".
@Kevin That can be as well but we can't know where this string comes from. What if it is an input from outside, right? Replacing separators in a string usually a bad idea.
@Kevin Yes but these kind of answers do not encourage learning.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.