tags:

views:

76

answers:

2

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
Notice that this is standard British usage - "European" doesn't include UK. That strip of water makes a big difference!
neil
+2  A: 

In python 3.1 you can use the thousands format specifier:

>>> ',.2f'.format(1234567.89)
'1,234,567.89'
Mike Axiak
This feature is a bit incomplete, as it doesn't consider alternate formats such as the common `.` instead of `,`.
Mark Ransom
True. The docs do discuss that a bit, and there are plans to make it more complete in future versions.
Mike Axiak