Skip to content

Instantly share code, notes, and snippets.

@rmpel
Created May 4, 2016 06:42
Show Gist options
  • Save rmpel/0bc2b211ea880c32107297afc4872ea5 to your computer and use it in GitHub Desktop.
Save rmpel/0bc2b211ea880c32107297afc4872ea5 to your computer and use it in GitHub Desktop.
Format numbers to human-readable format and money format (Euro, but easily adaptable)
if (!Number.prototype.format) {
Number.prototype.format = function(decimals, decimal_separator, thousands_separator, prefix, suffix) {
decimals = decimals || 0;
decimal_separator = decimal_separator || ',';
thousands_separator = thousands_separator || '.';
prefix = prefix || "";
suffix = suffix || "";
var str = this.toFixed(decimals).toString().split('.');
var parts = [];
for ( var i=str[0].length; i>0; i-=3 ) {
parts.unshift(str[0].substring(Math.max(0,i-3),i));
}
str[0] = parts.join(thousands_separator);
return prefix + str.join(decimal_separator) + suffix;
};
}
if (!Number.prototype.money) {
Number.prototype.money = function() {
return this.format(2, ',', '.', '€ ');
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment