Welcome, guest | Sign In | My Account | Store | Cart

A quick function to comma separate thousands in an integer or float.

Python, 13 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import re

def comma_me(amount):
    orig = amount
    new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', amount)
    if orig == new:
        return new
    else:
        return comma_me(new)

f = 12345678
print comma_me(`f`)
Output: 12,345,678

Sometimes when working with integers that will be interpreted as monetary values, it is necessary to format the integer into a string containing commas between the thousands boundaries. This is a simple recursive regexp function to do just that. It is easily confused if your integer or float doesn't really look like one, but stick to just those input values and it will work fine.

2 comments

Lloyd Kvam 19 years, 2 months ago  # | flag

Note that the locale module includes a format function that will insert commas (or periods) in your numbers:

locale.format("%.2f", num, 1)

will convert num to a separated string with two decimal places.

Rod Montgomery 18 years, 1 month ago  # | flag

Commafying with locale. locale.format( '%.2f', xx, 1 ) commafies but only if you do locale.setlocale(locale.LC_ALL, '') first.

Created by Michael Soulier on Sat, 24 Aug 2002 (PSF)
Python recipes (4591)
Michael Soulier's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks