[Tutor] Formatting Numbers as Strings 33000.50 -> 33,000.50 ?

Remco Gerlich scarblac@pino.selwerd.nl
Wed, 28 Mar 2001 13:00:21 +0200


On Wed, Mar 28, 2001 at 06:00:10PM +0800, Jethro Cramp wrote:
> Thanks for everyone's help in sorting out the problems I was having with
> floating point numbers.
> 
> Now I have all my numbers and all the calculations done I would like to
> format the output for example if I have the numbers:
> 
> 3306525.45 and 510575.98
> 
> I would like to format them as:
> 
> 3,306,525.45 and 510,575.98
> 
> Now I could roll my own formatter but I am sure that this is such a common
> task that it must have be a standard feature/module of python. Unfortunately
> I lost my copy of New Riders Python Reference a few weeks ago and I can't
> find something specifically in the Python Documentation (should one of the
> options for % work?) so I am flailing in the dark.
> 
> Any and all suggestions much appreciated.

This is an internationalization issue. For instance, the notation above is
common in the US, but in .nl we would write 3.306.525,45.

The solution should be in the locale module. Unfortunately on my weird Linux
system it's not working well, but something like the following should work:

import locale
locale.setlocale(locale.LC_ALL, "us")  # Try to set it to US, fails for me
print locale.format("%f", 3306525.45)

-- 
Remco Gerlich