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

前端 未结 12 2183
有刺的猬
有刺的猬 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:04

    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'
    

提交回复
热议问题