royalrekesh
royalrekesh

Reputation: 47

C# String Array to Double

Looking for some assistance. I'm sure its really easy, but I just cannot seem to get my head around it.

First, here's my code so far:

        //Prompts user to enter numbers
    Console.Write("Enter a line of comma-seperated temperatures: ");
    string temps = Console.ReadLine();
    //Splits commas, seperating numbers into array
    string[] numsInString = temps.Split(',');
    int temps1 = numsInString.Length;
    int[] temps2 = new int[temps1];
    for (int i = 0; i < numsInString.Length; i++)
    {
        temps2[i] = int.Parse(numsInString[i]);
    }


    Console.WriteLine("Minimum temp: " + temps2.Min());
    Console.WriteLine("Average temp: " + temps2.Average());

So, it prompts the user to enter a temperature i.e "5" separated by commas, "5,6,7,8". My trouble is that I cannot have temperatures in the decimal range such as "5.4,5.7,6.3,6.8". I've figured out that I need to convert the string to double, but I'm not entirely sure on how to do that.

Thanks

Upvotes: 0

Views: 4767

Answers (2)

Fabio
Fabio

Reputation: 32455

As already mentioned in other answers and comments you need change int[] array to double[] array and use double.Parse method for parsing strings to double.

But instead of loop or LINQ, I want suggest Array.ConvertAll method which will convert array of string to array of doubles.

Console.Write("Enter a line of comma-seperated temperatures: ");
var rawData = Console.ReadLine();
var rawTemperatures = rawData.Split(',');  
var temperatures = Array.ConvertAll<string, double>(rawTemperatures, double.Parse);

Array.ConvertAll method will execute same for loop, but will be tiny tiny (in your case) more effective and enough declarative then LINQ approach

Upvotes: 1

Charles Mager
Charles Mager

Reputation: 26213

You want to change the type of your array to double[] and then change your parsing to parse double instead of int:

double[] temps2 = new double[temps1];

for (int i = 0; i < numsInString.Length; i++)
{
    temps2[i] = double.Parse(numsInString[i]);
}

As a bit of an aside, you can also use LINQ to express this more declaratively:

double[] temps2 = temps.Split(',')
    .Select(double.Parse)
    .ToArray();

Upvotes: 2

Related Questions