How can I format a decimal to always show 2 decimal places?
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:
- the Python String Format Cookbook: shows examples of the new-style
.format()
string formatting -
pyformat.info: compares the old-style
%
string formatting with the new-style.format()
string formatting
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'
The String Formatting Operations section of the Python documentation contains the answer you're looking for. In short:
"%0.2f" % (num,)
Some examples:
>>> "%0.2f" % 10
'10.00'
>>> "%0.2f" % 1000
'1000.00'
>>> "%0.2f" % 10.1
'10.10'
>>> "%0.2f" % 10.120
'10.12'
>>> "%0.2f" % 10.126
'10.13'