Skip to content

Instantly share code, notes, and snippets.

@rd13
Created October 20, 2012 21:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rd13/3924792 to your computer and use it in GitHub Desktop.
Save rd13/3924792 to your computer and use it in GitHub Desktop.
PHP number_format in Javascript
//UK format - commas for thousands separator, full stop for decimal.
//d = number of decimal points.
String.prototype.number_format = function(d) {
var n = this;
var c = isNaN(d = Math.abs(d)) ? 2 : d;
var s = n < 0 ? "-" : "";
var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + ',' : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + ',') + (c ? '.' + Math.abs(n - i).toFixed(c).slice(2) : "");
}
console.log(
'2234324.99'.number_format()
);
//2,234,324.99
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment