How can I format a decimal to always show 2 decimal places?

orokusaki picture orokusaki · Jan 3, 2010 · Viewed 491.9k times · Source

I want to display:

49 as 49.00

and:

54.9 as 54.90

Regardless of the length of the decimal or whether there are are any decimal places, I would like to display a Decimal with 2 decimal places, and I'd like to do it in an efficient way. The purpose is to display money values.

eg, 4898489.00

Answer

BioGeek picture BioGeek · Jan 20, 2012

You should use the new format specifications to define how your value should be represented:

>>> from math import pi  # pi ~ 3.141592653589793
>>> '{0:.2f}'.format(pi)
'3.14'

The documentation can be a bit obtuse at times, so I recommend the following, easier readable references:

Python 3.6 introduced literal string interpolation (also known as f-strings) so now you can write the above even more succinct as:

>>> f'{pi:.2f}'
'3.14'