Convert string to float - decimal separator

I am having a problem with the following code:

string latString = "50.09445";
float lat = Convert.ToSingle(latString);

The second command throws a FormatException. I know that the problem is that the culture settings that I use (cs-CZ) use a comma as a delimiter with separators, and instead this line contains a decimal point.

Is there an easy way to “ignore” culture settings and always use a decimal point for conversion? Or should I just avoid the problem by first checking the line and replacing the comma with a decimal point?

+5
source share
4 answers

Use CultureInfo.InvariantCulture

float lat = Convert.ToSingle("50.09445", CultureInfo.InvariantCulture);
+19
source

Convert.ToSingle(string, IFormatProvider) ( - CultureInfo, )

float lat = Convert.ToSingle(latString, CultureInfo.InvariantCulture);
+2
string latString = "50.09445";
float lat = float.Parse(latString, CultureInfo.InvariantCulture);
+2
source
Single.Parse(latString, System.Globalization.CultureInfo.InvariantCulture);
+1
source

All Articles