Skip to main content
Participant
May 20, 2025
Question

Average Calculation Ignoring 0's and blank spaces

  • May 20, 2025
  • 3 replies
  • 301 views

Some one help me please. I know nothing about Javascript, but I am trying to make my job easier. I need to create three text boxes that average the values of certain fields on a form. My fields are named A1-A33. I need one box that averages A1-A22, one box that averages A23-A33 and one that averages A1-A33. The issue I am running into is that I need the averages to exclude 0s and blank spaces from the equation. So if I only have A1-A14 with values in them, the number dispalyed in the first text box will be the average of 14 values instead of the average of 22 values. Again I have no background in Javascript so if some one could explain this to me as if I am a child that would be fantastic.

3 replies

try67
Community Expert
Community Expert
May 21, 2025

I wrote and posted here a function that allows you to easily do it. Search the forum for "calcAverage".

Nesa Nurani
Community Expert
Community Expert
May 20, 2025

Name your 3 text fields: "Average 1-22", "Average 23-33" and "Average 1-33" and place this script on one of those fields as custom calculation script:

var sum1 = 0, count1 = 0;
var sum2 = 0, count2 = 0;
var sumAll = 0, countAll = 0;

for (var i=1; i<=33; i++) {
 var field = this.getField("A" + i);
 if (field) {
  var strVal = field.valueAsString;
  var numVal = parseFloat(strVal);

  if (!isNaN(numVal) && numVal !== 0) {
   sumAll += numVal;
   countAll++;

  if (i<=22) {
   sum1 += numVal;
   count1++;} 
  else {
   sum2 += numVal;
   count2++;}}}}

this.getField("Average 1-22").value = (count1 > 0) ? (sum1 / count1).toFixed(2) : "";
this.getField("Average 23-33").value = (count2 > 0) ? (sum2 / count2).toFixed(2) : "";
this.getField("Average 1-33").value = (countAll > 0) ? (sumAll / countAll).toFixed(2) : "";
Thom Parker
Community Expert
Community Expert
May 20, 2025

This type of calculation requires a script.  

Here's an example of the average calculation for A1-A22.

var nSum = 0, nCnt = 0;
var nVal;
for(var i=1;i<=22;i++)
{
    nVal = this.getField("A" + i).value;
    // Test value to ensure it is not empty, it's a number, and it's not zero
    if(!/^\s*$/.test(nVal) && !isNaN(nVal) && !nVal){
         nSum += Number(nVal);
         nCnt++;
    }
}
if(nCnt && nSum)
   event.value = nSum/nCnt;
else
   event.value = 0;

 

 

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often