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

Jethro Cramp jsc_lists@rock-tnsc.com
Wed, 28 Mar 2001 22:06:23 +0800


> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> Remco Gerlich
> Sent: Wednesday, March 28, 2001 7:00 PM
> To: tutor@python.org
> Subject: Re: [Tutor] Formatting Numbers as Strings 33000.50 -> 33,000.50
>
>
> 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)
>
Thank you. I had thought that it must be possible through the locale module
and had played with it in the interpreter but hadn't understood the "format"
in locale.format("format", val) part of the method. I have tried your
suggestion and several variations. Here are the results below (Windows ME,
Python 2.0):

>>> x = 33456.12
>>> locale.format("%f", x)
'33456.120000'
>>> locale.format("%d", x)
'33456'
>>> locale.format("%e", x)
'3.345612e+004'
>>> locale.format("%E", x)
'3.345612E+004'
>>> locale.format("%g", x)
'33456.1'
>>> locale.format("%G", x)
'33456.1'
>>> locale.format("%i", x)
'33456'
>>> locale.format("%u", x)
'33456'
>>> locale.format("%i", x)
'33456'

Some of these are expected, but still none of them are X,XXX.XX. Is this
some peculiarity of my system (will try it on my Linux box tomorrow)? Or
should I be using the locale.format() function differently. The idea of
being able to change the formatting just by changing the locale is very
appealing (I have clients all over Europe and formatting output to their
locale would be appreciated by them).

This leads me then to the question of how does one use the locale module to
format a monetary value? If you have a value in (say) DEM what function
would use to have it output correctly?

TIA,

Jethro