Skip to content

Instantly share code, notes, and snippets.

@mbunge
Last active August 29, 2015 14:16
Show Gist options
  • Save mbunge/13e5f61f0842167c3dad to your computer and use it in GitHub Desktop.
Save mbunge/13e5f61f0842167c3dad to your computer and use it in GitHub Desktop.
Formatting numbers in Javascript with correct rounding. Binding as Prototype to number.
//Plain method
var numberFormat = function (number, decPlaces, decSeparator, thouSeparator) {
decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;
decSeparator = decSeparator == undefined ? "." : decSeparator;
thouSeparator = thouSeparator == undefined ? "," : thouSeparator;
var roundAndReduceDecimals = function (num, length) {
return Math.round(num * Math.pow(10, length)) / Math.pow(10, length);
};
var format = function(n, decPlaces, decSeparator, thouSeparator){
var sign = n < 0 ? "-" : "",
i = parseInt(n) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};
return format(roundAndReduceDecimals(number, decPlaces), decPlaces, decSeparator, thouSeparator);
};
//prototyping to Number object
Number.prototype.formatNumber = function(decPlaces, decSeparator, thouSeparator){
return numberFormat(this, decPlaces, decSeparator, thouSeparator);
};
//example:
var n = 198.6859;
n.formatNumber(2, ',', '.');
//n = 198,69
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment