55.85 rounds to 55.8 (correct)
55.850 rounds to 55.8 (correct)
55.851 rounds to 55.9 (incorrect)
55.8501 rounds to 55.9 (Incorrect)
Here is the script:
var d = decimalPlaces || 0;
var m = Math.pow(10, d);
var n = +(d ? num * m : num).toFixed(8); // Avoid rounding errors
var i = Math.floor(n), f = n - i;
var e = 1e-8; // Allow for rounding errors in f
var r = (f > 0.5 - e && f < 0.5 + e) ?
((i % 2 == 0) ? i : i + 1) : Math.round(n);
return d ? r / m : r;
Any idea how this could be fixed?
Thanks so much
You should ask the people who wrote this code. This is not something PDF-specific, but a generic JS code.
Try67 is right this is not Acrobat specific code and I think it is rounding correctly ( as per the values, i.e. 55.851 > 55.85 and therefore rounds up) but if you round in stages then I believe you would get the answers you are looking for.
using 55.851 as the starting value.
call bankersRound ( 55.851, 2) // round to one less place than it currently has
result is 55.85
call bankersRound ( 55.85, 1)
result is 55.8 ( your expected result).
this could be done in a loop
// Replace Field names as appropriate.
var curValueToRound = this.getField("Text4").value;
// just making sure we have a string
var valueAsString = "" + initialValue;
// Assuming the number only has one decimal point in it
var numOfDigitsAfterDecimal = valueAsString.split(".").length
// loop until we get to the desired decimal place ( 1)
for ( i = tempValue - 1; i >= 1; i--)
curValueToRound = bankersRound ( curValueToRound, i);
this.getField("Text8").value = curValueToRound;
Your understanding of Bankers' Rounding is different than mine, and presumably different than the author of the script. All the results you quote seem correct to me.
Have you tried to respond to the source of your code.
There are a number of ways to round, Wikipedia rounding.
You need to clearly state how you expect the rounding to work and for your examples what your expected answer is.