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?
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.
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.
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.
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.
Use CultureInfo.InvariantCulture
float lat = Convert.ToSingle("50.09445", CultureInfo.InvariantCulture);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With