number format

Tony Meyer t-meyer at ihug.co.nz
Wed Jul 21 19:44:15 EDT 2004


[Josh Close] 
> How do I do a number format in python? Like with php's 
> number_format() function you can do 
> 
> number_format(1000) 
> 
> and it will return 
> 
> 1,000 

[Facundo Batista]
> You have a draft that I did for a money class based
> on decimal: 

To a man with a hammer, everything looks like a nail <wink>.

If you're not doing money, then the locale functions might do what you want
(if your default locale matches the format that you're after, or you're
happy to change locales, possibly temporarily).

>>> import locale
>>> locale.setlocale(locale.LC_ALL, "")
'English_New Zealand.1252'
>>> locale.format("%d", 1000, 1)
'1,000'

(Note that you *do* need the setlocale call there - if you leave it out,
you'll just get '1000'.)

It's also simple enough to write a function to do this:

<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146461>

=Tony Meyer




More information about the Python-list mailing list