Search code examples
c#arrayssum

Convert monetary string to array and total


I'm using c#, I have a string of cash entries I need to add together and get the total

arrTotalSplitCosts.Text = "24.90,10.60,1.90,20";

While the below works, as soon as I add a decimal point or a string value to replace the numbers in the array with my generated numbers, the below crashes

int[] arr = new int[] { 1, 2, 3 };
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
 sum += arr[i];
}

I want to take these values from a form post:

arrTotalSplitCosts.Text = "24.90,10.60,1.90,20";

And total them e.g. Total = 57.40

Anyone got any ideas, I'm struggling, thanks in advance.


Solution

  • The input is a string (not an array of string, but a single string).

    You then have to take that string and split it into a list or array.

    The values have decimals, so they cannot be dealt with as int. int is an integer; a whole number. You should deal with your data as a list of doubles.

    When you convert from string to double, you should use tryparse, as you can more stringently enforce the conversion and check for exceptions as you go.

    I've put a sample below, but note that I made it much more verbose than I normally would, just to (hopefully) more clearly show each of the steps.

    If I was going to actually do this, I would use Linq more and combine multiple steps into single lines.

    So something like this:

        using System;
        using System.Collections.Generic;
        using System.Linq;
                            
        public class Program
        {
            public static void Main()
            {
                Console.WriteLine("Hello World");
                var inString = "24.90,10.60,1.90,20";
                
                var stringValues = inString.Split(',');
                List<double> doubleValues = new List<double>();
                
                foreach(string v in stringValues){
                    double outNum;
                    double num = double.TryParse(v, out outNum)? outNum : 0;
                    doubleValues.Add(num);
                }
                
                Console.WriteLine(doubleValues.Sum(i => i)); // output = 57.4
            }
        }