I have a long string with double-type values separated by #
-value1#value2#value3#
etc
I splitted it to string table. Then, I want to convert every single element from this table to double type and I get an error. What is wrong with type-conversion here?
string a = "52.8725945#18.69872650000002#50.9028073#14.971600200000012#51.260062#15.5859949000000662452.23862099999999#19.372202799999250800000045#51.7808372#19.474096499999973#"; string[] someArray = a.Split(new char[] { '#' }); for (int i = 0; i < someArray.Length; i++) { Console.WriteLine(someArray[i]); // correct value Convert.ToDouble(someArray[i]); // error }
The strtod() is a builtin function in C and C++ STL which interprets the contents of the string as a floating point number and return its value as a double. It sets a pointer to point to the first character after the last valid character of the string, only if there is any, otherwise it sets the pointer to null.
Description. The atof() function converts a character string to a double-precision floating-point value.
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.
There are 3 problems.
1) Incorrect decimal separator
Different cultures use different decimal separators (namely ,
and .
).
If you replace .
with ,
it should work as expected:
Console.WriteLine(Convert.ToDouble("52,8725945"));
You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use InvariantCulture
(What is the invariant culture) e.g. using double.Parse
:
double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);
You should also take a look at double.TryParse
, you can use it with many options and it is especially useful to check wheter or not your string is a valid double
.
2) You have an incorrect double
One of your values is incorrect, because it contains two dots:
15.5859949000000662452.23862099999999
3) Your array has an empty value at the end, which is an incorrect double
You can use overloaded Split
which removes empty values:
string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
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