Skip to content

Instantly share code, notes, and snippets.

@joshprice
Created May 21, 2009 03:16
Show Gist options
  • Save joshprice/115251 to your computer and use it in GitHub Desktop.
Save joshprice/115251 to your computer and use it in GitHub Desktop.
String.prototype.reverse = function() {
return this.split("").reverse().join("");
}
Number.prototype.formatAsCurrency = function() {
return this.toString()
.replace(/^(\d)$/, "00$1") // pad 1 digit
.replace(/^(\d{2})$/, "0$1") // pad 2 digits
.reverse()
.replace(/(\d{2}(?=\d))/, "$1.") // place decimal point
.replace(/(\d{3}(?=\d))/g, "$1,") // place commas
.reverse();
}
(1).formatAsCurrency(); //=> "0.01"
(12).formatAsCurrency(); //=> "0.12"
(123).formatAsCurrency(); //=> "1.23"
(12345678).formatAsCurrency(); //=> "123,456.78"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment