edgarmtze
edgarmtze

Reputation: 25058

How to split a string into doubles and add them to array C#

I have a string like

"1.898, -1.456, 233.556, 34546.8"

How would I make an array of doubles in C# Do I have to use regex or split function?

I was trying something like:

string[] aux = ORIGINALtext.Split(',');
foreach (string val in aux)
{
   double value = double.Parse(val);
   Console.WriteLine(value);

}

Upvotes: 3

Views: 6876

Answers (4)

Markus Jarderot
Markus Jarderot

Reputation: 89241

A few different ways:

ORIGINALtext.Split(',').Select(s =>
        float.Parse(s, CultureInfo.InvariantCulture));

ORIGINALtext.Split(',').Select(s =>
        Convert.ToDouble(s, CultureInfo.InvariantCulture));

foreach (string s in ORIGINALtext.Split(',')) {
    double x;
    if (double.TryParse(s, NumberStyles.Number,
                        CultureInfo.InvariantCulture, out x)) {
        yield return x;
    }
}

CultureInfo.InvariantCulture will make the compiler use a consistent format across all country lines. (Dot for decimal separator, Comma for thousand separator, etc.)

With NumberStyles, you can control which number styles you want to allow (surrounding white space, signed numbers, thousand separator, etc.). You can also pass it to float.Parse, but not to Convert.ToDouble.

Upvotes: 2

csano
csano

Reputation: 13716

You could split the string using the comma delimiter and then use Double.Parse() to parse the individual string elements into doubles.

var s = "1.898, -1.456, 233.556, 34546.8";
var split = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var doubles = new double[s.Length];
for(var i=0; i < split.Length; i++) {
    doubles[i] = Double.Parse(split[i].Trim());
}

Upvotes: 1

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68747

double[] doubles = Array.ConvertAll(myDoubles.Split(','), double.Parse);

Or using LINQ

double[] doubles = myDoubles.Split(',').Select(double.Parse).ToArray();

Upvotes: 14

Scott
Scott

Reputation: 999

string[] str = "1.898, -1.456, 233.556, 34546.8".Split(',');
double[] doubles = new double[str.Length];
for (int i = 0; i < str.Length; i++)
{
    doubles[i] = double.Parse(str[i]);
}

Upvotes: 2

Related Questions