Login or Sign up

String format two decimal places in python (money)

Posted by: skyl on Jan. 20, 2010

String formatting in Python is powerful and more so with the still new format method. One bit of syntax that I can't always remember is how to simply force a number to display with two decimal places. The docs really tell you everything. But maybe all you really need right now is this:

>>> d=Decimal(50)
>>> f=50.009
>>> i=50
>>> for a in (d,f,i):
...     '%0.2f' % a         # the old way
...     '{0:.2f}'.format(a) # the new way
...
...
'50.00'
'50.00'
'50.01'
'50.01'
'50.00'
'50.00'

Don't be ashamed to visit the tutorial section as it is more chalk full of real world examples than the big dog library docs.

Comments on This Post:

Please Login (or Sign Up) to leave a comment