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
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:
.format()
string formatting%
string formatting with the new-style .format()
string formattingPython 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'