# Is there an average method for apex math

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?

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;
``````
• Depending on what's being averaged you might run out of room in the data type that you choose (salesforce.com/us/developer/docs/apexcode/Content/…). You just want to be sure that you choose the correct data type for the total (e.g., Long vs. Integer) and if the total can be larger than the maximum Long you'll probably need to modify this algorithm. Commented Aug 30, 2012 at 13:24
• The weirdest thing is that in many ways the excel-like formula and visualforce functions have cooler features than the underlying code. Has anyone put forth a community-built math methods class with all the tests included? If not, what a great project idea. Could totally be a nice appexchange thing. Commented Aug 31, 2012 at 2:49
• @ShaneMcLaughlin - Not exactly what you are describing, but there are some libraries such as apex-commons: salesforce.stackexchange.com/q/392. It could be added into that similar to how apache commons has a math library: commons.apache.org/math Commented Sep 1, 2012 at 0:53

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;
}
• `mean` is the same as what's meant with `average` in the question. Commented Aug 23, 2017 at 21:36
• Much better now. Although I believe you will see performance improvements using `Double` rather than `Decimal`. Also a bit brittle since it would fail on an empty list, or a null one (though null collections should be avoided where possible). Commented Aug 23, 2017 at 22:03