Skip to content

Instantly share code, notes, and snippets.

@gustavlrsn
Last active March 16, 2017 22:13
Show Gist options
  • Save gustavlrsn/9526530a4269b81a4212c0687c0fc859 to your computer and use it in GitHub Desktop.
Save gustavlrsn/9526530a4269b81a4212c0687c0fc859 to your computer and use it in GitHub Desktop.
A toFixed method using bankers rounding
// A toFixed method using bankers rounding
var toFixedBankers = function(value, precision) {
// precision = checkPrecision(precision, lib.settings.number.precision);
// value = unformat(value);
var exponentialForm = Number(value + 'e' + precision);
// i = integer part, f = fractional part
var i = Math.floor(exponentialForm), f = exponentialForm - i;
var rounded = f === 0.5 ? ((i % 2 == 0) ? i : i + 1) : Math.round(exponentialForm);
var finalResult = Number(rounded + 'e-' + precision).toFixed(precision);
return finalResult;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment