Created
July 4, 2012 11:21
-
-
Save anderssvendal/3046842 to your computer and use it in GitHub Desktop.
CoffeeScript price formatter
This file contains hidden or 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
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