An array of C#, PHP, and HTML programming articles, tutorials, and resources

Posts Tagged ‘ double ’

Calculating the Average from a List of numbers is accomplished through this easy function. The average is the sum of all values in a list divided by the total number of values. In this average example, we will assume the List consists of doubles (by means of a Generic List). For this to workOur Generic List is defined below:

List<double> myGenericDoubleList = new List<double>();
myGenericDoubleList.Add(5.2);
myGenericDoubleList.Add(8.4);
myGenericDoubleList.Add(435);
myGenericDoubleList.Add(76.9);
myGenericDoubleList.Add(3256.1);
myGenericDoubleList.Add(-85.2);

Now that we have defined our Generic Double List, we need to define our average function. Our function will take in a list of double values (the one we previously defined as myGenericDoubleList) and return a double value (which is our final double value). The average function reads in all double values and adds the value to a running sum. Finally, we divide the running sum by the total number of items in the list.

private double getAverage(List<double> doubleList)
{
    double total = 0;
    foreach (double value in doubleList)
    {
        total += value;
    }
    double average = total / doubleList.Count;
    return average;
}

Now that the function is ready to be used, we simply need to call the average function. An example is provided below:

double finalAverage = getAverage(myGenericDoubleList);

And there you have our complete example. Also important to know is a function has been provided out of the box with .NET Framework 3.5 that calculates the average of a list. To access this function, you be required to have a Generic List of double.

double finalDouble = myGenericDoubleList.Average()

A provided function of C# in the Math class is the function Round. The round function has two inputs. The first input field is of type double and the number requiring rounding. The second input type is of type int and indicates the precision of the first input field. This round function allows you to provide a degree of precision to your numbers.

public static double Round(double value, int digits)

A few important facts:

  1. When double value is rounded, if it is less than 5, it is rounded down. If it is equal to or greater than 5, the value is rounded up.
  2. Valid int digits are integer between 0 to 14.
  3. An int digit value of 0 will output a whole number.

Provided below is an working example:

double example = 12.34567;
double output = Math.Round(example, 3);

The value output in the above example equal 12.346.