Skip to main content
Inspiring
March 11, 2022
Answered

Javascript maths calculation (SUM, COUNTIF)

  • March 11, 2022
  • 1 reply
  • 3197 views

Hi, I'm hoping someone can help me urgently on this one...

 

I have the following formula in excel, but not sure how to change it so it works as Java in the custom calculation field in Acrobat (I've used some online tools but none seem to work).

  • =SUM(B2:Q2)/(13*(COUNTIF(B2:Q2,"<>")))*100

 

JS wise, this where I've got to....not very far:

  • event.value = ( this.getField("FINALscoreS1").value + this.getField("FINALscoreS2").value + this.getField("FINALscoreS3").value );

 

There'll be a number of 'FINALscoreS#' fields (yet to be decided). and what I'm after is:

The sum of all results in the 'FINALscoreS#' fields, divided by the sum of 13*however many 'FINALscoreS#' have a value (even if that value is zero...so ignoring any blanks).

(And then multiplied by 100 to give a percentage - the excel formula works perfectly if that's any use)

 

Does that makes sense? Can anyone help?? Pretty sure there'll be an array involved somewhere...

 

Huge thanks in advance...I expect for a JS guru this is as simple as 2+2, apologies!!

 

🙂

This topic has been closed for replies.
Correct answer bebarth

Hi,

Try that and let me know if I didn't understand someting.

 

var nb=numberOfFields;
var theSum=0;
var noBlank=0;
for (var i=1; i<=nb; i++) {
	theSum+=Number(this.getField("FINALscoreS"+i).value);
	if (this.getField("FINALscoreS"+i).valueAsString!="") noBlank++;
}
event.value=theSum*100/(13*noBlank);

 

@+

1 reply

bebarth
Community Expert
bebarthCommunity ExpertCorrect answer
Community Expert
March 11, 2022

Hi,

Try that and let me know if I didn't understand someting.

 

var nb=numberOfFields;
var theSum=0;
var noBlank=0;
for (var i=1; i<=nb; i++) {
	theSum+=Number(this.getField("FINALscoreS"+i).value);
	if (this.getField("FINALscoreS"+i).valueAsString!="") noBlank++;
}
event.value=theSum*100/(13*noBlank);

 

@+

Inspiring
March 11, 2022

Hi Bebarth,

 

Thanks so much for answering.

Unfortunately I'm only getting a result of 0, no matter what value is in the 'FINALscoreS#' fields.

Reading the code (from my limited understanding) it looks like you've understood what I'm after, it's just not working as it should...Thanks again for trying to help, it's hugely appreciated 🙂

 

P.S. The fields are on separate pages...that didn't used to make any difference as far as a I remember, but thought I'd mention it just in case.

Inspiring
March 11, 2022

ooooh...the "FINALscoreS" fields are calculated fields. They work fine as it's simple x+x...would that matter?

Thanks again