Skip to content

Instantly share code, notes, and snippets.

@eduardosilva
Created July 15, 2014 11:38
Show Gist options
  • Save eduardosilva/16c45f72c855b0466dff to your computer and use it in GitHub Desktop.
Save eduardosilva/16c45f72c855b0466dff to your computer and use it in GitHub Desktop.
Format number in javascript
Number.prototype.formatNumber = function (decimalPlaces, thousandsSeparator, decimalSeparator) {
decimalPlaces = isNaN(decimalPlaces = Math.abs(decimalPlaces)) ? 2 : decimalPlaces;
decimalSeparator = decimalSeparator == undefined ? "." : decimalSeparator;
thousandsSeparator = thousandsSeparator == undefined ? "," : thousandsSeparator;
var number = this.toFixed(decimalPlaces);
if (decimalPlaces) {
var i = number.substr(0, number.length - (decimalPlaces + 1));
var j = decimalSeparator + number.substr(-decimalPlaces);
} else {
i = number;
j = '';
}
function reverse(str) {
var result = '';
for (var l = str.length - 1; l >= 0; l--) {
result += str.charAt(l);
}
return result;
}
if (parseInt(i)) {
i = reverse(reverse(i).replace(/(\d{3})(?=\d)/g, "$1" + thousandsSeparator));
}
return i + j;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment