Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to float conversion - decimal separator

Tags:

c#

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?

like image 589
Ondra C. Avatar asked Jun 17 '10 07:06

Ondra C.


People also ask

How do you convert a string to a floating point number?

The atof() function converts a character string to a double-precision floating-point value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.

How do you convert float to decimal?

The rules for converting a floating point number into decimal are simply to reverse of the decimal to floating point conversion: If the original number is in hex, convert it to binary. Separate into the sign, exponent, and mantissa fields. Extract the mantissa from the mantissa field, and restore the leading one.

What does atof mean in C?

atof is a function in the C programming language that converts a string into a floating point numerical representation. atof stands for ASCII to float. It is included in the C standard library header file stdlib.

How do you convert a comma separated string to a float in Python?

To convert a string with comma separator and dot to a float:Use the str. replace() method to remove the commas from the string. Use the float() class to convert the string to a floating-point number.


2 Answers

Use CultureInfo.InvariantCulture

float lat = Convert.ToSingle("50.09445", CultureInfo.InvariantCulture);
like image 172
simendsjo Avatar answered Nov 15 '22 08:11

simendsjo


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);
like image 37
lc. Avatar answered Nov 15 '22 08:11

lc.