-1

I want to convert a string to float

bool numbFloat = float.TryParse(operatorsOperand[0], out float numFloat);
System.Console.WriteLine(numFloat);
return result;

For example: I have a string[0] where the number 5,4 is..when I convert it to float and then print it, 54 appears, it appears like that regardless of which conversion method I use, float.Parse, TryParse, Convert...

3
  • 1
    What is operatorsOperand? What is result? Can you update this to a minimal reproducible example which can be independently tested to demonstrate the problem? Commented Dec 10, 2024 at 14:36
  • 6
    Chances are this boils down to a locale/culture issue. "5,4" in some European countries would be 5.4. Not so in most other countries, where "." is the decimal-separator. So, if the current culture is not for example de-de, then the string "5,4" will be parsed to "54" because that "," would be ignored (or if using strict parsing, it would fail). Commented Dec 10, 2024 at 14:40
  • 1
    Afaik it is recommended to be explicit about the culture you want to parse in. That way the underlying system culture doesn't matter (that much). If you know you are going to parse German or French - formatted numbers, pass the respective culture. Commented Dec 10, 2024 at 14:43

1 Answer 1

3

If you use a specific culture that use , as the decimal separator, it works as expected

var de = System.Globalization.CultureInfo.CreateSpecificCulture("de-DE");
bool numbFloat = float.TryParse("5,4", de, out float numFloat);
System.Console.WriteLine(numFloat);

Live example: https://dotnetfiddle.net/tVxF1E

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

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.