Skip to content

Instantly share code, notes, and snippets.

@cognitom
Created July 26, 2013 16:14
Show Gist options
  • Select an option

  • Save cognitom/6090162 to your computer and use it in GitHub Desktop.

Select an option

Save cognitom/6090162 to your computer and use it in GitHub Desktop.
Format numbers with comma.
numberFormat = (n) ->s = n + ''; s = s.replace(/(\d+)(\d{3})$/, '$1,$2') while /(\d+)(\d{3})$/.test s; s
numberFormat2 = (n) -> (n + '').replace /(\d+)(\d{3})?(\d{3})?(\d{3})?(\d{3})?(\d{3})$/, (match...) -> (match[p] + '' for p in [1..6] when match[p]).join ','
numberFormat3 = (n) -> (n = '00' + n).substr(n.length % 3).match(/\d{3}/g).reduce((x,y) -> x + ',' + y if y).replace /^0*/, ''
numberFormat4 = (n) -> (n + '').split('').reduceRight (x, y) -> if (x.length + 1) % 4 then y + x else y + ',' + x
# usage
s = numberFormat4 1234567 # "1,234,567"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment