首页 > 解决方案 > 如何将有效数字的数量限制为 * 不超过 * 不超过 str.format() 或 f-strings 的数量?

问题描述

我可以做类似的事情

'Correct answers: {:.2f}'.format(value)

对于 3.141592 的值,这将根据需要返回 3.14。然而,对于 0 的值,它将返回 0.00,正如预期的那样,但不是预期的那样。在这种情况下,我想看到“0”。可能吗?

标签: pythonstringformatting

解决方案


我认为您正在寻找:

'Correct answers: {}'.format(round(5.666666, 2))
'Correct answers: {}'.format(round(5.6, 2))
'Correct answers: {}'.format(round(5, 2))
'Correct answers: {}'.format(round(0, 2))

输出:

Correct answers: 5.67
Correct answers: 5.6
Correct answers: 5
Correct answers: 0

推荐阅读