Skip to main content
Participant
Mar 12, 2025 1:41 PM UTC
Answered

Complex Calculation Treating Negative Numbers as Zero in PDF Form

 

I need a javascript for Complex Calculation where Total + SAI + Pell = Need; but if SAI is a negative number, treat as zero. Can anyone please assist me? 

Nesa Nurani
Nesa NuraniCorrect answer
Community Expert
Mar 12, 2025 2:22 PM UTC

Use this in "Need" field as custom calculation script:

var total = Number(this.getField("Total").valueAsString);
var sai = Number(this.getField("SAI").valueAsString);
var pell = Number(this.getField("Pell").valueAsString);

event.value = total + Math.max(0, sai) + pell;

5 replies

Nesa Nurani
Community Expert
Nesa NuraniCommunity ExpertCorrect answer
Community Expert
Mar 12, 2025 2:22 PM UTC

Use this in "Need" field as custom calculation script:

var total = Number(this.getField("Total").valueAsString);
var sai = Number(this.getField("SAI").valueAsString);
var pell = Number(this.getField("Pell").valueAsString);

event.value = total + Math.max(0, sai) + pell;
Translate
Participant
Mar 12, 2025 2:42 PM UTC

Thanks, Nesa! 

Translate
Rene Andritsch
Community Expert
Community Expert
Mar 12, 2025 2:18 PM UTC

Hi @jeremy_1903 when looking for scripts to validate or calculate something in Acrobat I found that ChatGPT returns very useful code. Please check the code if it does exactly what you are looking for because it was generated.

 

For your example this would be:

 

// Function to safely get a numeric value from a field
function getFieldNumber(fieldName) {
    var field = this.getField(fieldName);
    return field && field.valueAsString !== "" ? Number(field.valueAsString) : 0;
}

// Get values from form fields
var pell = getFieldNumber("pell");
var sai = Math.max(0, getFieldNumber("sai")); // Ensure SAI is non-negative
var total = getFieldNumber("total");

// Calculate the sum
var need = pell + sai + total;

// Set the calculated value in the "need" field
this.getField("need").value = need;

 

See a screen capture of it working here:

 

 

Translate
Participant
Mar 12, 2025 2:41 PM UTC

I didn't even consider ChatGPT, thats a great idea for the future. Thank you so much for your help! 

Translate
Rene Andritsch
Community Expert
Community Expert
Mar 12, 2025 2:46 PM UTC

But here you can also see that Nesa’s code is much shorter and probably more efficient. ChatGPT can be used as a starting point but as you can see below it is great to have the assistance of a professional coder.

Translate