38

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?

Community
  • 1
  • 1
ensnare
  • 40,069
  • 64
  • 158
  • 224

4 Answers4

102

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 3
    -1 Unfortunately this is **broken**; it perpetuates the legacyness of the locale module -- **it doesn't work properly with unicode**. Try `format(1234, u"n")` in a locale (e.g. French, Russian) where the thousands separator is a NO-BREAK SPACE. You get the newbies' favourite exception: `UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 ...` – John Machin Nov 02 '10 at 23:10
  • 1
    @John Machin: For the record, most of the upvotes were made to this answer before I added the Note about using `locale` -- and for everyone's enlightenment, just what *is* the currently correct why to the operation in a locale-specific manner that will handle Unicode? Thanks. – martineau Nov 02 '10 at 23:24
  • (1) When the upvotes were made is of what relevance?? (2) There is no Python-2.X-supported enlightenment, just a kludge: `format(1234, "n").decode(locale.getpreferredencoding())` :-( – John Machin Nov 03 '10 at 02:25
  • 8
    OK, using `locale` for this in Python 2.x doesn't work for Unicode strings. My bad (even though I never claimed it did). If the locale is set to French, `format(1234, "n")` results in `1 234` with no exceptions raised. **Question for you:** Why haven't you also downvoted or at least commented on the other answers here that suggest using `locale` as their prime answer? – martineau Nov 03 '10 at 11:55
  • The {,} formatting also works with floats: for example `'{:,.2f}'.format(mydollars)` formats in dollars and cents. – fantabolous Jul 28 '14 at 09:19
  • @fantabolous: That's exactly what I meant by "It works with **floats**, ints, and decimals — and all the other formatting features provided for in the mini-language spec" (emphasis added). – martineau Nov 10 '17 at 17:19
13

locale.format()

Don't forget to set the locale appropriately first.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • And don't forget to specify a `True` value for the optional _grouping_ argument, as in `locale.format(u'%d', 1234, True)` for example. Apparently `locale` isn't completely inept at handling Unicode (as @John Machin's comments in another answer seem to suggest). – martineau Jun 12 '12 at 17:25
12

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.

Community
  • 1
  • 1
systempuntoout
  • 71,966
  • 47
  • 171
  • 241
  • 2
    +1 despite the docstring, looks like it handles floating point as well as integer numbers. The use of the variable names "dollars" and "cents", aside from being somewhat overly application-centric, seem to support this hypothesis. Very Python version portable, as presented will work back to version 2.3, and if the `enumerate()` iterator was replaced with the something equivalent, all the way back to version 2.0. – martineau Oct 12 '10 at 15:39
  • 2
    For Python 2.4+, the `str(dollars)[::-1]` could be replaced with the more readable `reversed(str(dollars))`. – martineau Oct 12 '10 at 15:48
  • @martineau nice review, I use this function on Google App Engine where Python is limited to 2.5 version out of the box. – systempuntoout Oct 12 '10 at 16:17
  • This guy doesn't work well for negative numbers: -,123,456.00 – fileoffset Oct 15 '12 at 01:47
  • Isn't dollars already a string before you do `str(dollars)` in enumerate? – letmutx May 08 '16 at 06:17
  • awesome function, ty – Marko Bajlovic Oct 16 '19 at 13:49
5

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)
Aphex
  • 7,390
  • 5
  • 33
  • 54