Skip to main content
Participant
June 7, 2019
Answered

Am I able to limit the decimal places in a JavaScript calculation?

  • June 7, 2019
  • 2 replies
  • 2798 views

I have used the following code in a pdf document.    event.value = ( this.getField("Rent").value / this.getField("Month").value ) * this.getField("Days").value. I have formatted the field for two decimal places. When I total several of these calculations in a later field it is sometimes off by .01. While the field is rounding the number, it is using the actual number with many places after the decimal point in adding multiple fields together.

This topic has been closed for replies.
Correct answer Thom Parker

Formatting controls the appearance of the field data, but the value is the same.

So you need to change the decimal places in the actual field value.

Try this.

var nValue = ...Your calculation...

event.value = Number(util.printf("%0.2f",nValue));

This code code uses the print function to create a string version of the number with the correct number of digits, and then converts it to a number.

From a coding perspective this is easier than trying to use math to cut off the decimal places. Programming purest would have a problem with it.

2 replies

Thom Parker
Community Expert
Thom ParkerCommunity ExpertCorrect answer
Community Expert
June 7, 2019

Formatting controls the appearance of the field data, but the value is the same.

So you need to change the decimal places in the actual field value.

Try this.

var nValue = ...Your calculation...

event.value = Number(util.printf("%0.2f",nValue));

This code code uses the print function to create a string version of the number with the correct number of digits, and then converts it to a number.

From a coding perspective this is easier than trying to use math to cut off the decimal places. Programming purest would have a problem with it.

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
Participant
June 7, 2019

Thank you Thom. This worked the magic I needed.

Bernd Alheit
Community Expert
Community Expert
June 7, 2019

You must round the calculated value.