Formula to calculate the average of a number of fields
I am trying to write a formula in java script to calculate the average of 42 numbers, where some of the fields can be empty.
I am trying to write a formula in java script to calculate the average of 42 numbers, where some of the fields can be empty.
I've developed a function that allows you to do it easily. The basic code is:
/*
@17537118
aFields : an array of the field names to use for the calcluation
bIgnoreBlanks : a boolean that tells the function whether or not to ignore blank fields
bIgnoreZeros : a boolean that tells the function whether or not to ignore zero values
*/
function calcAverage(aFields, bIgnoreBlanks, bIgnoreZeros) {
var total = 0;
var n = 0;
for (var i in aFields) {
var f = this.getField(aFields[i]);
if (f==null) {
console.println("Error! Can't locate a field called: " + aFields[i]);
continue;
}
if (f.valueAsString=="" && bIgnoreBlanks) continue;
var v = Number(f.valueAsString);
if (isNaN(v)) continue;
if (v==0 && bIgnoreZeros) continue;
total+=v;
n++;
}
if (n==0) event.value = "";
else event.value = total/n;
}
You can then call it from the field's calculation script like this:
calcAverage(["Field1", "Field2", "Field3"], true, false);
Edit: Fixed some small spelling mistakes in the code
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.