barteloma
barteloma

Reputation: 6875

How to split a string and convert it to an array of doubles

I have text like this:

const string geometryText = "POINT(-71.064544 42.28787)";

I want to get numeric values as a double array:

string[] lineStrings = geometryText.Split('(', ')')[1].Split(' ');

double[] lines = Array.ConvertAll(lineStrings, Convert.ToDouble);

This returns an array but values are not valid, it returns :

-71064544.0 and 4228787.0

How can I get this to work? Regex?

Upvotes: 0

Views: 1900

Answers (2)

BhavO
BhavO

Reputation: 2399

Use invariant culture when converting to double, different cultures will parse numbers differently based on what commas and periods mean in that culture, some cultures use . as a group seperator for example.

double[] lines = Array.ConvertAll(lineStrings, i => Convert.ToDouble(i, CultureInfo.InvariantCulture));

It works here:

https://dotnetfiddle.net/UEjFaH

Upvotes: 3

D Stanley
D Stanley

Reputation: 152644

The problem may be that the periods are interpreted as thousands separators instead of decimal separators. If you want to ensure that periods are always interpreted as decimal points regardless of the machine culture use double.Parse with a specified culture:

double[] lines = lineStrings.Select(s => double.Parse(s, CultureInfo.InvariantCulture))
                            .ToArray();

Upvotes: 6

Related Questions