These forums are now Read Only. If you have an Acrobat question, ask questions and get help from one of our experts.

Rounding Up

Flashmyster
Registered: Dec 9 2007
Posts: 11

Hello:

I am a new member. I am in the process of designing a Form with calculated fields. In one of the calculations a given number (in another field) has to be multiplied by 2 and then Rounded Up to the closest 1,000.

For example:

63,250 X 2= 126,500 and then rounding to the nearest 1,000, the result should be 127,000. How can I accomplish this in custom calculation?

I would appreciate any and all help. Thank you very much.

gkaiseril
Expert
Registered: Feb 23 2006
Posts: 4308
One would have to use the JavaScript "Math.round()" method that rounds to the nearest integer. So to round to the nearest thousand, one needs to shift the decimal place, round and restore the original decimal location.

var quantity = 63250;
var price = 2;
var result = quantity * price;
console.show();
console.println("Extended value: " + result);
result = result / 1000; // shift decimal by 1000
console.println("Shifted value: " + result);
result = Math.round(result); // round to nearest integer
console.println("Rounded to integer value: " + result);
result = result * 1000; // restore decimal to original location
console.println("Restored value: " + result);

George Kaiser

gkaiseril
Expert
Registered: Feb 23 2006
Posts: 4308
A more generalized solution using functions and being able to specify the input value and the decimal unit one wants the result rounded to:

The following functions can be placed as a document level function or folder function:

function Round(sInput) {
// return input as integer from round inputted number formatted to 3 decimals
var fNumber = Number(sInput); // force to number
var sNumber3 = util.printf('%0 .3f', fNumber); // force to 3 rounded decimal place string
var fNumber3 = Number(sNumber3); // force back to number
return Math.round(fNumber3); // round to whole number
} // end Round

function RoundNearest(sInput, sDecimal) {
/*
Round to nearest decimal value
Math.round - rounds to nearest whole number
Multiply input to 1/Decimal to obtain number of Decimals
Round converted input to whole number
Multiply by Decimal to return to nearest whole decimal value
*/
var fInput = Number(sInput); // convert to number
var fDecimal = Number(sDecimal); // convert number
if (fDecimal == 0) { // test for divide by zero
app.alert('sDecimal must be a number! ' + sDecimal, 0, 1);
return ''; // force exit
}
var fNumber = fInput / fDecimal; // convert to units of sDecimal for rounding
var fRound = Round(fNumber); // round to whole numbers
return (fRound * fDecimal); // return in whole decimal units
} // end function RoundNearest


The event's Custom calculation script becomes:

event.value = RoundNearest(this.getField('Input').value, 1000)

George Kaiser