Skip to main content
New Participant
March 12, 2025
Answered

Complex Calculation Treating Negative Numbers as Zero in PDF Form

  • March 12, 2025
  • 2 replies
  • 779 views

 

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? 

Correct answer Nesa Nurani

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;

2 replies

Nesa Nurani
Nesa NuraniCorrect answer
Community Expert
March 12, 2025

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;
New Participant
March 12, 2025

Thanks, Nesa! 

Rene Andritsch
Community Expert
March 12, 2025

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:

 

 

New Participant
March 12, 2025

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

Rene Andritsch
Community Expert
March 12, 2025

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.