Coder Perfect

How can I print a number with thousands separators using commas?


In Python 2.6.1, I’m trying to display an integer with commas as thousands separators. I’d like to display the number 1234567 as 1,234,567, for example. I’m not sure how I’d go about doing this. I’ve found a lot of examples on Google, but I’m seeking for the most practical solution.

It is not necessary to choose between periods and commas based on your location. I’d like something as straightforward as possible.

Asked by Elias Zamaria

Solution #1

'{:,}'.format(value)  # For Python ≥2.7
f'{value:,}'  # For Python ≥3.6
import locale
locale.setlocale(locale.LC_ALL, '')  # Use '' for auto, or force e.g. to 'en_US.UTF-8'

'{:n}'.format(value)  # For Python ≥2.7
f'{value:n}'  # For Python ≥3.6

Mini-Language Format Specification,

Answered by Ian Schneider

Solution #2

This is how I got it to work:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US')
>>> locale.format("%d", 1255000, grouping=True)

Sure, you don’t need internationalization support, but it’s clear, concise, and uses a built-in library.

P.S. The “percent d” formatter is the standard percent formatter. You can only have one formatter, but it can be whatever field width and precision setting you require.

P.P.S. If you can’t get locale to function, I’d recommend modifying Mark’s response:

def intWithCommas(x):
    if type(x) not in [type(0), type(0L)]:
        raise TypeError("Parameter must be an integer.")
    if x < 0:
        return '-' + intWithCommas(-x)
    result = ''
    while x >= 1000:
        x, r = divmod(x, 1000)
        result = ",%03d%s" % (r, result)
    return "%d%s" % (x, result)

Recursion is useful in the negative case, but I think one recursion per comma is overkill.

Answered by Mike DeSimone

Solution #3

I’m amazed no one has highlighted that you can accomplish something as easily as this with f-strings in Python 3.6+:

>>> num = 10000000
>>> print(f"{num:,}")

… where the format specifier is the part after the colon. Because the comma is the desired separating character, f”num:_” uses underscores instead of a comma. This technique only accepts the characters “,” and ” .”

This is equivalent of using format(num, “,”) for older versions of python 3.

When you first see it, it may appear to be magical, but it is not. It’s just a part of the language, and it’s something that’s frequently used enough to warrant a shortcut. Look at the group subcomponent for further information.

Answered by Emil Stenström

Solution #4

It’s difficult to beat the following for inefficiency and readability:

>>> import itertools
>>> s = '-1234567'
>>> ','.join(["%s%s%s" % (x[0], x[1] or '', x[2] or '') for x in itertools.izip_longest(s[::-1][::3], s[::-1][1::3], s[::-1][2::3])])[::-1].replace('-,','-')

Answered by Kasey Kirkham

Solution #5

After deleting unnecessary bits and tidying it up a little, here is the locale grouping code:

(Note that the following only applies to numbers.)

def group(number):
    s = '%d' % number
    groups = []
    while s and s[-1].isdigit():
        s = s[:-3]
    return s + ','.join(reversed(groups))

>>> group(-23432432434.34)

There are already a few good responses in this thread. This is just something I wanted to note for future reference. There will be a format specifier for thousands separator in Python 2.7. It works like this, according to the Python documentation.

>>> '{:20,.2f}'.format(f)

You can perform the same thing in Python 3.1 by typing:

>>> format(1234567, ',d')

Answered by Nadia Alramli

Post is based on