Skip to content

Instantly share code, notes, and snippets.

@duncanbeevers
Created March 4, 2010 17:34
Show Gist options
  • Save duncanbeevers/321934 to your computer and use it in GitHub Desktop.
Save duncanbeevers/321934 to your computer and use it in GitHub Desktop.
Format numbers as comma-delimited strings
//= require <prototype>
// (2001000).withDelimiters(); // "2,001,000"
// (9821).withDelimiters("_"); // "9_821"
// (1221).withDelimiters(",", 100); // "12,21"
Number.prototype.withDelimiters = function(s, k) {
if (!s) s = ",";
if (!k) k = 1000;
var o = [],
i = Math.floor(this);
while(i) {
o.unshift(i % k);
i = Math.floor(i / k);
}
return [ o.shift() ].concat(o.map(function(t) {
return t.toPaddedString(((k - 1) + '').length);
})).join(s);
};
@JerrySievert
Copy link

value.toFixed(0).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment