CFLib.org – Common Function Library Project

averageWithoutZeros(data)

Last updated January 12, 2004

Version: 1 | Requires: ColdFusion 5 | Library: MathLib

 
Rated 0 time(s). Average Rating: 0

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:

view plain print about
<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:

view plain print about
<cfscript>
/**
 * 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;
}
</cfscript>
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Tayo Akinmade Tayo Akinmade added
arrayTrim
11 day(s) ago

Will Belden Will Belden added
longTime
17 day(s) ago

James Sleeman James Sleeman added
quickSort
27 day(s) ago

Ben Forta Ben Forta added
GetHostAddress
30 day(s) ago

Top Rated

Darwan Leonardo Sitepu EksporSQLData
Rated 5.0, 16 time(s)

Darwan Leonardo Sitepu backupDatabase
Rated 5.0, 13 time(s)

Barney Boisvert indentXml
Rated 5.0, 10 time(s)

Kevin Pepperman generateSsccAsn
Rated 5.0, 4 time(s)

Created by Raymond Camden / Design by Justin Johnson