Blake Walters

Commafy - Pretty Numbers for Python

Penned on .

I've been spending more and more time in Python and Django lately working on side project lostaga.in and Viget Ms. Pac-Man.  Here's a quick method I put together for formatting numbers with commas:

def commafy(d):
  s = '%0.2f' % d
  a,b = s.split('.')
  l = []
  while len(a) > 3:
      l.insert(0,a[-3:])
      a = a[0:-3]
  if a:
      l.insert(0,a)
  return ','.join(l)