Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to double in C#

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 } 
like image 675
whoah Avatar asked Jul 09 '12 16:07

whoah


People also ask

What is strtod in C?

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.

What function will convert a string into a double-precision quantity?

Description. The atof() function converts a character string to a double-precision floating-point value.

What is atof 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.


1 Answers

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);

like image 106
Zbigniew Avatar answered Sep 25 '22 22:09

Zbigniew