Skip to content

Instantly share code, notes, and snippets.

@Razoxane
Forked from FrankFang/banker_round.js
Created February 24, 2016 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Razoxane/9b96bb8ce9c35117611d to your computer and use it in GitHub Desktop.
Save Razoxane/9b96bb8ce9c35117611d to your computer and use it in GitHub Desktop.
Gaussian/Banker's Rounding in JavaScript
function evenRound(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;
}
console.log( evenRound(1.5) ); // 2
console.log( evenRound(2.5) ); // 2
console.log( evenRound(1.535, 2) ); // 1.54
console.log( evenRound(1.525, 2) ); // 1.52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment