Currency format for floats?

jepler epler jepler.lnk at lnk.ispi.net
Fri Jun 2 19:17:38 EDT 2000


On Thu, 1 Jun 2000 19:20:31 +0200, Joseph Santaniello
 <joseph at src.no> wrote:
>Hi,
>
>I have an SQL query which I can format to give me a nice value like
>23,342.40 which Python squashes into 23342.4 when I stick it into a
>list element. Is there a nice way to format floats so they look like
>(US) currency?

According to the Linux manpage for printf(3), the following flag
can be included in a format specifier:
              '      specifying that in a numerical argument  the
                     output is to be grouped if the locale infor-
                     mation indicates any.  Note that  many  ver-
                     sions  of  gcc  cannot parse this option and
                     will issue a warning.
The manpage doesn't note that this is a nonstandard extension to printf
(as it does for the use of q, ll, and L), so I am lead to understand
that this conforms to ANSI C3.159-1989 (``ANSI C'').

However, 1.6a1 gives:
	>>> print "%'f" % 66666.666
	Traceback (most recent call last):
	  File "<stdin>", line 1, in ?
	ValueError: unsupported format character ''' (0x27)
i.e., no go---this isn't directly supported yet.

If you have locale enabled, and I don't, it looks like locale.format
will return a string in the desired format, and local.ato[if] will make
that string into an integer/float again.

These techniques, to the extent that they work, will make your program
behave correctly in *all* locales (or at least, more than one), for
instance those which use . for the thousands separator and , for the
decimal point.

Jeff



More information about the Python-list mailing list