CFLib.org – Common Function Library Project

averageWithoutZeros(data)

Last updated January 12, 2004

author

David Simms

Version: 1 | Requires: CF5 | Library: MathLib

Description:
ColdFusion's built-in arrayAvg() function calculates an average by taking the sum of a set of numbers and then dividing that sum by the total count of the numbers. When the set of numbers contains one or more zeros, this produces an inaccurate average when the developer wishes to average only those values which are greater than or equal to 1.

Return Values:
Returns a number.

Example:

<cfset data = listToArray("5,0,5,3,0")>
<cfoutput>
Built-in ArrayAvg: #arrayAvg(data)#<br>
AverageWithoutZeros: #averageWithoutZeros(data)#
</cfoutput>

Parameters:

Name Description Required
data The array to average. Yes

Full UDF Source:

/**
 * Calculates the average of a set of numbers omitting values less than 1 from that average.
 * 
 * @param data 	 The array to average. (Required)
 * @return Returns a number. 
 * @author David Simms (dsimms@dcbar.org) 
 * @version 1, January 12, 2004 
 */
function averageWithoutZeros(data) {
	var counter = arrayLen(data);
	
	//remove zeros
	for(;counter gte 1;counter=counter-1) {
		if(data[counter] lt 1) arrayDeleteAt(data,counter);
	} 

	if(arrayLen(data)) return arrayAvg(data);
	else return 0;
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson