Limiting floats to two decimal points

前端 未结 28 3138
你的背包
你的背包 2020-11-21 04:57

I want a to be rounded to 13.95.

>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999

The ro

28条回答
  •  孤独总比滥情好
    2020-11-21 05:10

    Nobody here seems to have mentioned it yet, so let me give an example in Python 3.6's f-string/template-string format, which I think is beautifully neat:

    >>> f'{a:.2f}'
    

    It works well with longer examples too, with operators and not needing parens:

    >>> print(f'Completed in {time.time() - start:.2f}s')
    

提交回复
热议问题