You need to sign in to do that

Don't have an account?

Baird_S

# Method for calculating median

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.add(1); testvalues.add(2); testvalues.add(3); //testvalues.add(4); 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

Anup Jadhav

Like it, but I don't the round() and divide() method since they introduce imprecision when it's not required.

I'd do something like Wikipedia says we should do to calculate sample median:

Code:

## All Answers

Anup Jadhav

Like it, but I don't the round() and divide() method since they introduce imprecision when it's not required.

I'd do something like Wikipedia says we should do to calculate sample median:

Code:

Baird_SThanks, Anup. Good to have some code up for people to use.

Ruzan MorrisonIs there a suggestion on how to use Median calculation on a dashboard or in a report? Paul SchembriHey all!

I'll apologise in advance for my lack of dev understanding.

Hopefully my question makes sense!

But is some of the code above a potential workaround to get the 'median' in some reporting?

If so, is it possible for the original posters to elaborate a little more on how it can be used?

Im looking to get the Median on how long particular cases have been 'Open' in SalesForce.

Thanks