Formate a number with commas

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Thu Feb 9 16:13:10 EST 2012


noydb <jenn.duerr at gmail.com> writes:

> How do you format a number to print with commas?

>>>> import locale
>>>> locale.setlocale(locale.LC_ALL, "")

This sets the locale according to the environment (typically LANG---I'm
talking about linux, don't know others).

>>>> locale.format('%d', 2348721, True)
> '2,348,721'

This would not give the same result in environments with other locales
(typically de or fr or ...)

Anyway, it's probably the right thing to do: the user will get numbers
written according to its own locale.

If you really want commas whatever locale you're running in, you will
need to use setlocale to change number formatting to a locale that uses
commas. For instance:

locale.setlocale(LC_NUMERIC,"en_US.utf8")
locale.format('%d', 2348721, True)

-- Alain.



More information about the Python-list mailing list