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
}
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: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. usingdouble.Parse: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 validdouble.2) You have an incorrect double
One of your values is incorrect, because it contains two dots:
15.5859949000000662452.238620999999993) Your array has an empty value at the end, which is an incorrect double
You can use overloaded
Splitwhich removes empty values:string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);