The JavaScript symbols for the math operations of addition (+), subtraction (-), division ( / ), and multiplication ( * ) are the same as Excel. However, the plus sign can also be used for concatenation of text strings. For example, "dog"+"house" returns doghouse. The Acrobat JavaScript engine will usually interpret numbers as numbers. However, there are some cases where numbers get interpreted as strings. If a number interpreted as a string is part of an addition equation, it will be concatenated. Try these in the console:
4+4 //returns 8
"4"+"4" //returns 44
"4"+4 //returns 44
4+4+4 //returns 12
4+4+"4" //returns 84
4.5+4.5 //returns 9
"4.5"+4.5 //returns 4.54.5
For the other 3 operations, string numbers will be interpreted as numbers:
"4"*4 //returns 16
"4"*"4" //returns 16
"4"/"4" //returns 1
"4"-"4" //returns 0
Avoiding Concatenation
If the expected sum is 8 and the result is 44, it probably means the two 4’s were interpreted as strings and concatenated. To force strings to be interpreted as numbers to the plus sign generates addition, rather than concatenation, use the Number( ) method:
event.value = this.getField("FieldA").value + this.getField("FieldB").value;
//Becomes
event.value = Number(this.getField("FieldA").value) +
Number(this.getField("FieldB").value);
NaN
In Mathematical Errors Part I I discussed how division by zero returns Infinity which produces the pop up formatting error alert when the field is formatted for numbers. The error can also occur if NaN (“not a number”) is forced into a field that is formatted to accept a number. To troubleshoot the formatting error, remove the formatting to see the value being pushed into the field.
NaN occurs when the expected result is a number but the result is not. Concatenation of two decimal numbers (see first code block example 4.54.5) can cause this, but also any math calculation that ends up pulling in a text string, array, object, or anything else that makes results in Not a Number.
Calculation Order Matters
As the heading says, calculation order matters. In correct calculation order can lead to incorrect math results. See the following article are:
PDF Field Calculation Order Matters
Fortunately, there’s an easy fix that allows the form designer to configure the calculation order correctly by moving calculated fields up or down to correct the order.