A quick function to comma separate thousands in an integer or float.
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.
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.
Commafying with locale. locale.format( '%.2f', xx, 1 ) commafies but only if you do locale.setlocale(locale.LC_ALL, '') first.