Ondra C.
Ondra C.

Reputation: 2522

string to float conversion - decimal separator

I'm having a problem with the following code:

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

The second command throws a FormatException exception. I know that problem is that culture settings I'm using (cs-CZ) use comma as decimal separator and this string contains decimal point instead.

Is there some easy way to "ignore" the culture settings and always use decimal point for the conversion? Or should I just avoid the problem by checking the string first and replace comma by the decimal point?

Upvotes: 6

Views: 17834

Answers (4)

KristoferA
KristoferA

Reputation: 12397

Single.Parse(latString, System.Globalization.CultureInfo.InvariantCulture);

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

string latString = "50.09445";
float lat = float.Parse(latString, CultureInfo.InvariantCulture);

Upvotes: 2

lc.
lc.

Reputation: 116458

Try the Convert.ToSingle(string, IFormatProvider) overload instead, and pass it the invariant culture (or whatever CultureInfo you want to be using instead):

float lat = Convert.ToSingle(latString, CultureInfo.InvariantCulture);

Upvotes: 2

simendsjo
simendsjo

Reputation: 4749

Use CultureInfo.InvariantCulture

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

Upvotes: 21

Related Questions