3

Possible Duplicate:
how to print number with commas as thousands separators in Python 2.x

Does anyone know of an easier way to make numbers have thousands separation than this:

def addComma(num):
    (num, post) = str(num).split('.')
    num = list(num)
    num.reverse()

    count = 0
    list1 = []

    for i in num:
        count += 1
        if count % 3 == 0:
            list1.append(i)
            list1.append(',')
        else:
            list1.append(i)

    list1.reverse()

    return ''.join(list1).strip(',') + '.' + post

It works, but it seems REALLY fragile...

Community
  • 1
  • 1
Soviero
  • 1,774
  • 2
  • 13
  • 23
  • This has been asked and answered a couple of times here: [1](http://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators-in-python-2-x), [2](http://stackoverflow.com/questions/3909457/whats-the-easiest-way-to-add-commas-to-an-integer-in-python), [3](http://stackoverflow.com/questions/5180365/python-add-comma-into-number-string) – Lev Levitsky Apr 09 '12 at 20:19

1 Answers1

3

Use locale.format() with grouping=True

>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, 'en_US')
'en_US'
>>> locale.format("%d", 1234567, grouping=True)
'1,234,456'

See http://docs.python.org/library/locale.html#locale.format for more information.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636