[Tutor] number formatting

Michael P. Reilly arcege@shore.net
Fri, 12 Jan 2001 12:16:57 -0500 (EST)

> Right now I'm trying to figure out how to format numbers as currency.  For
> example, I want to turn this: 1314403624.57
> into this: $1,314,403,624.57
> Now I can easily add a $ to the front of the string, but how do I get those
> commas in there? I'm currently using '%.2f' % myfloatingpointnumber to
> format it to two decimal places, is there another option which adds commas?

There are no string formatting options to do this.  So how about a
brute force approach:

def add_commas(number, decimal=2, howmany=3):
  import string
  s = '%.*f' % (decimal, number)
  whole, fract = string.split(s, '.')
  # make the string into a multiple of how many we want
  l = ((len(whole) / howmany) + 1) * howmany 
  zs = string.rjust(whole, l)
  # brake into groups of how many characters we want
  bucket = []
  while zs:
    part, zs = zs[:howmany], zs[howmany:]
  if bucket[0] == (' ' * howmany): # we have a bug?
    del bucket[0]
  commas = string.join(bucket, ',')
  return string.lstrip(string.join([commas, fract], '.'))

>From this you would just have to add the dollar sign.  There are
probably some nicer ways that I didn't invest time in thinking about
(like instead of padding the string, group from the end by "howmany"),
but this also gives you a view into some of the tools available.

Good luck,

| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |