0

I have a textbox, that is binded to a string variable. The input is 5.5 I need the string variable to calculate something but i noticed that float.parse(stringvariable) ignores the dot (makes it a 55).

Is there a way to fix this problem?

Thank you

Altan Asd
  • 47
  • 4
  • Can you give a [mre]? What is your Culture setting? – gunr2171 Feb 01 '21 at 16:34
  • 2
    Try entering `5,5` instead. – Blindy Feb 01 '21 at 16:34
  • 1
    check out a non exhaustive list of decimal separator from [Wikipedia](https://en.wikipedia.org/wiki/Decimal_separator) some use comma, other periods. Your app is running on a computer that has the culture set to one of those country. – Franck Feb 01 '21 at 16:42
  • 1
    Use the [overload method that accepts a culture](https://learn.microsoft.com/en-us/dotnet/api/system.single.parse?view=net-5.0#System_Single_Parse_System_String_System_IFormatProvider_) and pass the correct culture. – Magnetron Feb 01 '21 at 16:42
  • 3
    Does this answer your question? [float.Parse() doesn't work the way I wanted](https://stackoverflow.com/questions/1014535/float-parse-doesnt-work-the-way-i-wanted) – gunr2171 Feb 01 '21 at 16:43

2 Answers2

3

This is due to your default culture info. To accept decimal points which are . then can do this:

float f = float.Parse("float value as string", CultureInfo.InvariantCulture);

However if you're expecting , to be used then you can specify then you can specify a culture which does that like this:

float f = float.Parse("float value as string", new CultureInfo("fr-FR").NumberFormat);

Obviously can be any culture and don't have to use French!

Tom Dee
  • 2,516
  • 4
  • 17
  • 25
1

As stated by Tom Dee, this issue is related to your System.Globalization.CultureInfo settings.

You can modify this for the current thread by setting:

  • CurrentCulture
  • CurrentUICulture

i.e.

 Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

or

Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("it-IT");

to the CultureInfo object you need, as well as use the correct overload for the Parse method, previously highlighted.

linsock
  • 190
  • 1
  • 9