Skip to content

Instantly share code, notes, and snippets.

@9point6
Created October 16, 2013 09:28
Show Gist options
  • Save 9point6/7005108 to your computer and use it in GitHub Desktop.
Save 9point6/7005108 to your computer and use it in GitHub Desktop.
Formats a number with commas, and can shorten large numbers when surpassing a million. Implemented on number prototype,
Number.prototype.formatNum = ( decimal = true, millionify = 1 ) ->
if @ > 999999 && millionify
"#{( Math.round( @ / 100000 ) / 10 ).formatNum decimal, millionify - 1}m"
else
[n,d] = "#{@}".split '.'
reg = /(\d+)(\d{3})/
while reg.test n
n = n.replace reg, '$1,$2'
n + if d? and decimal then ( if not decimal then ".#{d.substr( 0 , decimal )}" else ".#{d}" ) else ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment