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
}
Add a class as Public and use it very easily like convertToInt32()
Then Call The Function
and successfully passed tests are:
Most people already tried to answer your questions.
If you are still debugging, have you thought about using:
This will help you in determining what is wrong in each of the string first before you do the actual parsing.
If you have a culture-related problem, you might consider using:
This http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx has a really good example on how to use them.
If you need a long, Int64.TryParse is also available: http://msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx
Hope that helps.
In your string I see:
15.5859949000000662452.23862099999999
which is not a double (it has two decimal points). Perhaps it's just a legitimate input error?You may also want to figure out if your last
String
will be empty, and account for that situation.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.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);