Skip to content

Instantly share code, notes, and snippets.

@ktusznio
Created October 26, 2012 08:08
Show Gist options
  • Save ktusznio/3957562 to your computer and use it in GitHub Desktop.
Save ktusznio/3957562 to your computer and use it in GitHub Desktop.
Dollarize helper in Coffeescript
dollarize = (n, currency = "$", decimals = 2,
decimalSeparator = ".", thousandsSeparator = ",") ->
if n instanceof String
n = parseInt n, 10
sign = if n < 0 then "-" else ""
wholeDigits = "" + Math.abs(n - (n % 1))
postThousands = if wholeDigits.length > 3
wholeDigits.length % 3
else
0
higherDigits = if postThousands > 0
wholeDigits.substr(0, postThousands) + thousandsSeparator
else
""
middleDigits = wholeDigits.substr(postThousands).replace(/(\d{3})(?=\d)/g, "$1" + thousandsSeparator)
decimalDigits = if decimals
decimalSeparator + Math.abs(n % 1).toFixed(decimals).substr(2)
else
""
currency + sign + higherDigits + middleDigits + decimalDigits
dollarize(-1234567.89) => $-1,234,567.89
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment