What's the easiest way to add commas to an integer?

Question:

Possible Duplicate:
How to print number with commas as thousands separators?

For example:

>> print numberFormat(1234)
>> 1,234

Or is there a built-in function in Python that does this?

Asked By: ensnare

||

Answers:

locale.format()

Don’t forget to set the locale appropriately first.

Stripped from webpy utils.py:

def commify(n):
    """
    Add commas to an integer `n`.

        >>> commify(1)
        '1'
        >>> commify(123)
        '123'
        >>> commify(1234)
        '1,234'
        >>> commify(1234567890)
        '1,234,567,890'
        >>> commify(123.0)
        '123.0'
        >>> commify(1234.5)
        '1,234.5'
        >>> commify(1234.56789)
        '1,234.56789'
        >>> commify('%.2f' % 1234.5)
        '1,234.50'
        >>> commify(None)
        >>>

    """
    if n is None: return None
    n = str(n)
    if '.' in n:
        dollars, cents = n.split('.')
    else:
        dollars, cents = n, None

    r = []
    for i, c in enumerate(str(dollars)[::-1]):
        if i and (not (i % 3)):
            r.insert(0, ',')
        r.insert(0, c)
    out = ''.join(r)
    if cents:
        out += '.' + cents
    return out

There are other solutions here.

Answered By: systempuntoout

Use locale.format() on the integer, but beware of the current locale on your environment. Some environments may not have this set or set to something that won’t give you a commafied result.

Here’s some code I had to write to deal with this exact issue. It’ll automatically set the locale for you depending on your platform:

try:
    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') #use locale.format for commafication
except locale.Error:
    locale.setlocale(locale.LC_ALL, '') #set to default locale (works on windows)

score = locale.format('%d', player['score'], True)
Answered By: Aphex

No one so far has mentioned the new ',' option which was added in version 2.7 to the Format Specification Mini-Language — see PEP 378: Format Specifier for Thousands Separator in the What’s New in Python 2.7 document. It’s easy to use because you don’t have to mess around with locale (but is limited for internationalization due to that, see the original PEP 378). It works with floats, ints, and decimals — and all the other formatting features provided for in the mini-language spec.

Sample usage:

print format(1234, ",d")    # -> 1,234
print "{:,d}".format(1234)  # -> 1,234
print(f'{1234:,d}')         # -> 1,234 (Python 3.6+)

Note: While this new feature is definitely handy, it’s actually not all that much harder to use the locale module, as several others have suggested. The advantage is that then numeric output can be made to automatically follow the proper thousands (and other) separator conventions used in various countries when outputting things like numbers, dates, and times. It’s also very easy to put the default settings from your computer into effect without learning a bunch of language and country codes. All you need to do is:

import locale
locale.setlocale(locale.LC_ALL, '')  # empty string for platform's default settings

After doing that you can just use the generic 'n' type code for outputting numbers (both integer and float). Where I am, commas are used as the thousand separator, so after setting the locale as shown above, this is what would happen:

print format(1234, "n")    # -> 1,234
print "{:n}".format(1234)  # -> 1,234

Much of the rest of the world uses periods instead of commas for this purpose, so setting the default locale in many locations (or explicitly specifying the code for such a region in a setlocale() call) produces the following:

print format(1234, "n")    # -> 1.234
print "{:n}".format(1234)  # -> 1.234

Output based on the 'd' or ',d' formatting type specifier is unaffected by the use (or non-use) of setlocale(). However the 'd' specifier is affected if you instead use the locale.format() or locale.format_string() functions.

Answered By: martineau
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.