Skip to content

Instantly share code, notes, and snippets.

@anderssvendal
Created July 4, 2012 11:21
Show Gist options
  • Save anderssvendal/3046842 to your computer and use it in GitHub Desktop.
Save anderssvendal/3046842 to your computer and use it in GitHub Desktop.
CoffeeScript price formatter
formatPrice = (price)->
return '0' if isNaN(price)
price = price + ''
price = price.split(/\./)
decimals = price[1]
price = price[0]
iterations = price.length / 3
i = price.length
segments = []
while i > 0
i = Math.max(0, i - 3)
length =
if i == 0 and parseInt(iterations) != iterations
price.length - (Math.floor(price.length / 3) * 3)
else
3
segments.unshift(price.substr(i, length))
result = segments.join(' ') + formatDecimals(decimals)
result
formatDecimals = (decimals)->
return '' unless decimals?
decimals = decimals + '0' if decimals.length == 1
decimals = decimals.substr(0,2) if decimals.length > 2
",#{decimals}"
console.log formatPrice(30000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment