Skip to content

Instantly share code, notes, and snippets.

@anderssvendal
Created July 4, 2012 11:21

Revisions

  1. anderssvendal revised this gist Jul 4, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion price.coffee
    Original file line number Diff line number Diff line change
    @@ -9,7 +9,7 @@ formatPrice = (price)->
    i = price.length
    segments = []
    while i > 0
    i = Math.min(Math.max(0, i - 3))
    i = Math.max(0, i - 3)
    length =
    if i == 0 and parseInt(iterations) != iterations
    price.length - (Math.floor(price.length / 3) * 3)
  2. anderssvendal created this gist Jul 4, 2012.
    29 changes: 29 additions & 0 deletions price.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    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.min(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)