2 Replies Latest reply on Apr 4, 2014 5:02 AM by ALeon

# Ratio in calcualted field

I am trying to create a field on an interactive form in Acrobat XI Pro that will create a ratio (A:B). I have two fields that the user will enter data (Number of Students and Number of Instructors). I want a third field (Ratio of Students to Instructors) that will create the ratio in the smallest possible value (i.e. 3:1, not 9:3).

I believe I need to use the Custom calculation script, but have not done this before. Any help would be appreciated.

I was trying this, but it obviously did not work:

//custom calculation script for ratio of students to instuctors

var cDivisor = "Number of Instuctors";
var cDividend = "Number of Students";

//clear field value in case no update

event.value = "";

//get the value of the fields

var nDivisor = this.getField(cDivisor).valueAsString;
var nDividend = this.getField(cDividend).valueAsString;

//process if non-blank, non-zero divisor

if(nDivisor != "" && Number(nDivisor) !=0 && !isNaN(Number(nDivisor))){
var x = nDivisor/nDividend;
event.value = x+":1";
}

• ###### 1. Re: Ratio in calcualted field

What you need to do is divide each number by the greatest common divisor of the two numbers, which is easy to calculate. Here are two functions you can use:

// Document-level functions

function gcd(a, b) {

// Recursive function to determine the greatest common divisor

// of two integers a and b

return b ? gcd(b, a % b) : a;

}

function getRatioString(x, y) {

// Create a ratio string given two numbers (assumed to be positive integers)

var d = gcd(x, y);

return "" + ( x / d ) + ":" + ( y / d );

}

You can then do something like:

// Custom calculation script

(function () {

// Get the field values, as numbers

// Assume validate scripts force positive integers

var x = +getField("a").value;

var y = +getField("b").value;

// Show the ratio string

event.value = x > 0 && y > 0 ? getRatioString(x, y) : "";

})();

but you should check that both numbers are positive integers somewhere. I'm assuming the fields have custom validate scripts that force positive integers.

• ###### 2. Re: Ratio in calcualted field

Thanks George,

That helps a great deal. I appreciate the assist.

Anthony Leon