The CreatorCon Call for Content is officially open! Get started here.

calculate average of fields and return the answer in another field

msjoy
Kilo Expert

how do you calculate mean score/average of fields and return the answer in another field

Joyce

2 REPLIES 2

Mike Allen
Mega Sage

You can do it in a business rule:



var numberArray = [current.field1, current.field2, current.field3], total = 0, average = 0;



for(var 1=0;i<numberArray.length;i++){


        total += numberArray[i];


}


average = total/numberArray.length;



current.field_avg = average;



Or you can do it in a set of onChange client scripts;



onChange field1



var numberArray = [newValue, g_form.getValue(field2), g_form.getValue(field3)], total = 0, average = 0;



for(var 1=0;i<numberArray.length;i++){


        total += numberArray[i];


}


average = total/numberArray.length;



g_form.setValue(field_avg) = average;



onChange field2



var numberArray = [g_form.getValue(field1), newValue,   g_form.getValue(field3)], total = 0, average = 0;



for(var 1=0;i<numberArray.length;i++){


        total += numberArray[i];


}


average = total/numberArray.length;



g_form.setValue(field_avg) = average;



onChange field3



var numberArray = [g_form.getValue(field1),   g_form.getValue(field2), newValue], total = 0, average = 0;



for(var 1=0;i<numberArray.length;i++){


        total += numberArray[i];


}


average = total/numberArray.length;



g_form.setValue(field_avg) = average;


Uncle Rob
Kilo Patron

Going to have to be javascript, something like this...



// Cute little trick I learned... you can declare multiple variables on the same line


var numbers=[field1,field2,field3,field4], total=0,avg=0;


// Declare a for loop and make a running total of the fields.


for(var i=0;i<numbers.length;i++) {


  total+=number[i];


}


// Calculate the average once the for loop has added everything up.


// Since the fields are all in an array, we just ask how long the array is.


avg=(total/number.length);   // place the avg variable in whatever field you want to store it.



So now the only problem is this is Server Side script, so it will only process after a transaction.   It won't dynamically change as you change the numbers on the form.   You'll need to commit a save first.





EDIT:   Ninja'd by Mike