I was doing some bill calculations, and went looking in the math method for an average.

Usage would be something like

- math.average(1, 4, 6, 7, 8, 9)
- math.average(ListOfIntegers)
- math.average(ListOfDecimals)

or same type of stuff with sets.

Spent about 15 minutes looking and googling. I know about SOQL aggregate, but this is lots of calc with lots of intermediate steps.

This must exist, right?

Attribution to: Shane McLaughlin

# Possible Suggestion/Solution #1

Unfortunately the standard math methods only include simpler operations (i.e. those that work on a single, or two values), **so it looks as though you'll have to roll your own method**.

Of course the number of script statements executed will be proportional to the length of the list, so of the lists are ever of a fixed size it could be worth using a macro to generate the addition part for you:

```
Int sum = i[0] + i[1] + ... i[n];
```

Doing so would only count for one statement, but you'll only need this if governor limits are of concern which is often not a worry.

If govenor limits aren't an issue you could create a function along these lines:

```
Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7};
Integer total = 0;
Double dAvg;
for (Integer i : myInts) {
total += i;
}
dAvg = Double.valueOf(total) / myInts.size();
return dAvg;
```

Attribution to: Matt Lacey

# Possible Suggestion/Solution #2

I have a small statistical library on github. It provides various measures of centrality and dispersion, including `Stats.mean`

:

```
public static Decimal mean(List<Decimal> nums) {
Decimal total = 0.0;
for (Decimal n : nums) {
total += n;
}
return total / nums.size();
}
```

Attribution to: ipavlic

This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/993