Skip to main content
hans-georgt40201113
Participant
March 13, 2019
Question

Acrobat Javascript Rechenfehler

  • March 13, 2019
  • 7 replies
  • 588 views

Hallo,

schwierig zu beschreiben aber vielleicht kennt jemand die Problematik zu nachstehenden vermeintlichen Rechenfehler in javascript das in einem PDF Formular eingesetzt wird.

Hier eine beispielhafte Rechnung:

1,15 - (1,15 * 0,05)

ergibt per Hand gerechnet eigentlich

1,0925

gebe ich diese Formel jedoch wie folgt als Berechnung in Acrobat ein

event.value =  1.15-(1.15*0.05)

ergibt diese Rechnung

1.0924999999999998

Frage:

Wieso werden hier Nachkommastellen eingefügt?

Wo ist hier mein Denkfehler?

Mein Problem ist, das sich dadurch Rundungsfehler im weiteren Verlauf der Berechnungen ergeben.

This topic is closed to new replies. Start a new post to keep the conversation going.

7 replies

try67
Community Expert
Community Expert
March 13, 2019

This is a complex issue relating to how computer languages (and computers in general) represent floating numbers.

You can read about it more in depth here: What Every JavaScript Developer Should Know About Floating Points - Modern Web

The solution is to manually round the results to a fixed number of decimals.

You can use the toFixed method for that (although note that it returns a string, not a number), or write a function that does it using the various built-in commands of the Math object (ceil, floor, round).

hans-georgt40201113
Participant
March 13, 2019

thank you for the really quick answer.

my problem with round is, that my client compares my calculation with excel . The calculation they do is simply using the excel-function to round-down to the 4th dezimal.

first example:

1.325-(1.325*0.05) = 1.256375 (result excel)

1.325-(1.325*0.05) = 1.256375 (same in javascript)

excel round down is: 1.2563

javascript would do the same: 1.2563

every thing is fine!

second example:

1.15-(1.15*0.05) = 1.0925  (result excel)

1.15-(1.15*0.05) =1.0924999999999998 (result in javascript)

excel round down is: 1.0925

javascript: 1.0924

And i have no clue how to fix that.

Do you?

try67
Community Expert
Community Expert
March 13, 2019

For example:

(1.15-(1.15*0.05)).toFixed(4)