<分区>
其他问题表明 Python f 字符串在特定小数位舍入数字,而不是截断它们。
我可以用下面的例子来说明这一点:
>>> number = 3.1415926
>>> print(f"The number rounded to two decimal places is {number:.2f}")
The number rounded to two decimal places is 3.14
>>>
>>> number2 = 3.14515926
>>> print(f"The number rounded to two decimal places is {number2:.2f}")
The number rounded to two decimal places is 3.15
然而,我遇到过另一种情况,Python 似乎截断了数字:
>>> x = 0.25
>>> f'{x:.1f}'
'0.2'
我原以为 0.25
会四舍五入为 0.3
,保留一位小数。我是否遗漏了什么,或者这种行为不一致?