Created
January 14, 2012 22:09
-
-
Save captainpete/1613071 to your computer and use it in GitHub Desktop.
dojo7-formatting-currency-in-javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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