Skip to content

Instantly share code, notes, and snippets.

@captainpete
Created January 14, 2012 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save captainpete/1613071 to your computer and use it in GitHub Desktop.
Save captainpete/1613071 to your computer and use it in GitHub Desktop.
dojo7-formatting-currency-in-javascript
Number.prototype.toCurrency = ->
match = (this / 100).toString().match(/^-?(\d+)(\.\d+)?$/)
return unless match
cents = if match[2] then (match[2] + '00').substr(1, 2) else '00'
dollars = match[1].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,')
result = "$#{dollars}.#{cents}"
result = '-' + result if this < 0
result
Number.prototype.toCurrency = function() {
var cents, dollars, match, result;
match = (this / 100).toString().match(/^-?(\d+)(\.\d+)?$/);
if (!match) return;
cents = match[2] ? (match[2] + '00').substr(1, 2) : '00';
dollars = match[1].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
result = "$" + dollars + "." + cents;
if (this < 0) result = '-' + result;
return result;
};
// Examples
433495.toCurrency(); // gives $4,334.95
-433495.toCurrency(); // gives -$4,334.95
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment