Comma separate strings and numbers in JavaScript

rob 24 Mar 2010
Comments Off

I recently had to format large numbers using JavaScript and was really missing Railsnumber_with_delimiter function. Heres a simple version for JavaScript.


// Allow strings to number_to_currency style comma seperate
String.prototype.commafy = function () {
return this.replace(/(^|[^w.])(d{4,})/g, function($0, $1, $2) {
return $1 + $2.replace(/d(?=(?:ddd)+(?!d))/g, "$&,");
});
}

// Convenience method for numbers
Number.prototype.commafy = function () {
return String(this).commafy();
}

Comments (0)

Comments are closed.