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

前端 未结 12 2009
有刺的猬
有刺的猬 2020-11-22 17:31

I want to display:

49 as 49.00

and:

54.9 as 54.90

Regardless of the length of the decimal

12条回答
  •  心在旅途
    2020-11-22 18:02

    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'
    

提交回复
热议问题