I can’t find this in documentation anywhere.
I have 5 fields. Weight 1, 2,3,4,5 . I want a stored calculation field that caculates the average of them.
I tried to define my calucation field "return avg(weight1,weight2,weight3…5)
But it does not work.
The only way i work around it now is "return (weight 1+2..5)/5
which doesn’t work well because if i only enter a value into weight 1, it assumes wieght2 thru weight 5 field are 0 and returns a wrong average.
PLEASE HELP!
Sammy,
Try this:
var ttlWeight = weight_1 + weight_2 + weight_3 + weight_4 + weight_5
var ttlFields = 0
if (weight_1 > 0){ttlFields += 1}
if (weight_2 > 0){ttlFields += 1}
if (weight_3 > 0){ttlFields += 1}
if (weight_4 > 0){ttlFields += 1}
if (weight_5 > 0){ttlFields += 1}
average_weight_field = ttlWeight / ttlFields
Hi Sammy,
No problem - here’s the code that I used (I used globals - but just substitute your field names). Also, make sure the return result is NUMBER - not integer (unless that’s what you want):
var count = 0
var total = 0
if(globals.num1)
{
total += globals.num1
count += 1
}
if(globals.num2)
{
total += globals.num2
count += 1
}
if(globals.num3)
{
total += globals.num3
count += 1
}
if(globals.num4)
{
total += globals.num4
count += 1
}
if(globals.num5)
{
total += globals.num5
count += 1
}
return total/count
Hope this helps.
Sammy,
Sorry about that. You did say a calculation field! Last line should read
return ttlWeight/ttlFields
bcusick:
Hi Sammy,
No problem - here’s the code that I used (I used globals - but just substitute your field names). Also, make sure the return result is NUMBER - not integer (unless that’s what you want):
var count = 0
return total/count
Hope this helps.
THANKS Bob and airmark,
this works great. Just weird to see how servoy doesn’t have a built in average function.