I have a bunch of numbers that I want to print to the user. Each number is greater than one million so I want to print it as 1.000.000 or 1,000,000 (any of these forms is valid to me). I want to know if is it possible to format integer numbers this way in python using the built-in formating utilities.
+7
A:
Use locale.format
. You will need to setlocale
first, since the formatting style is dependent on location (European countries typically use .
instead of ,
for separating the digits, for instance).
>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'English_United Kingdom.1252'
>>> locale.format("%d", 1000000000, grouping=True)
'1,000,000,000'
LC_ALL
sets the locale to the default, usually in the LANG
environment variable.
katrielalex
2010-09-29 13:28:32
Notice that this is standard British usage - "European" doesn't include UK. That strip of water makes a big difference!
neil
2010-09-29 14:12:07
+2
A:
In python 3.1 you can use the thousands format specifier:
>>> ',.2f'.format(1234567.89)
'1,234,567.89'
Mike Axiak
2010-09-29 13:39:02
This feature is a bit incomplete, as it doesn't consider alternate formats such as the common `.` instead of `,`.
Mark Ransom
2010-09-29 13:46:40
True. The docs do discuss that a bit, and there are plans to make it more complete in future versions.
Mike Axiak
2010-09-29 14:03:30