Bug in bankersRound script
I am using this bankers rounding script as a document level script that I found online, Gaussian/Banker's Rounding in JavaScript · GitHub . It works well except it's rounding weird when working with numbers with 3+ decimal places. For example:
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:
function bankersRound(num,decimalPlaces){
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
