Created
July 26, 2013 16:14
-
-
Save cognitom/6090162 to your computer and use it in GitHub Desktop.
Format numbers with comma.
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
| 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