• Paul Schembri
• NEWBIE
• 5 Points
• Member since 2020

• Chatter
Feed
• 0
• 0
• 0
Likes Given
• 0
Questions
• 1
Replies

I imagine this is pretty basic, but I haven't seen any code posted here to calculate the median of a list of numbers.  Here's mine, which could pretty easily be adapted to most uses:

```List<Integer> testvalues =
new List<Integer>();
Double Middle;

testvalues.sort();
decimal sizeOfList = testvalues.size();
system.debug('size of list is '+ sizeOfList);
Middle = sizeOfList.divide(2,1);
system.debug('middle of list is ' + Middle);
system.debug('minimum value is ' + testvalues[0]);
system.debug('max value is ' + testvalues[testvalues.size()-1]);
//Calculate median
if (middle <> middle.round()) {
system.debug('median is '+ testvalues[middle.intValue()]);
}
else {
decimal lowMedianValue = testvalues[middle.intValue()-1];
decimal highMedianValue = testvalues[middle.intValue()];
decimal Median = (lowMedianValue + highMedianValue)/2;
system.debug('median value is ' + Median);
}```

I hope that makes someone's day easier.

Baird