I am trying to print an integer in Python 2.6.1 with commas as thousands separators. For example, I want to show the number 1234567
as 1,234,567
. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.
It does not need to be locale-specific to decide between periods and commas. I would prefer something as simple as reasonably possible.
In Python, to format a number with commas we will use “{:,}” along with the format() function and it will add a comma to every thousand places starting from left. After writing the above code (python format number with commas), Ones you will print “numbers” then the output will appear as a “ 5,000,000”.
Artturi Jalli. To comma-separate thousands in a big number in JavaScript, use the built-in toLocaleString() method. It localizes the number to follow a country-specific number formatting. To separate thousands with commas, localize the number to the USA.
Using the modern f-strings is, in my opinion, the most Pythonic solution to add commas as thousand-separators for all Python versions above 3.6: f'{1000000:,}' . The inner part within the curly brackets :, says to format the number and use commas as thousand separators.
I got this to work:
>>> import locale >>> locale.setlocale(locale.LC_ALL, 'en_US') 'en_US' >>> locale.format("%d", 1255000, grouping=True) '1,255,000'
Sure, you don't need internationalization support, but it's clear, concise, and uses a built-in library.
P.S. That "%d" is the usual %-style formatter. You can have only one formatter, but it can be whatever you need in terms of field width and precision settings.
P.P.S. If you can't get locale
to work, I'd suggest a modified version of Mark's answer:
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 for the negative case, but one recursion per comma seems a bit excessive to me.
'{:,}'.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
Per Format Specification Mini-Language,
The
','
option signals the use of a comma for a thousands separator. For a locale aware separator, use the'n'
integer presentation type instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With