f字符串十进制格式舍入

问题描述

其他问题表明,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到小数点后一位。我是否缺少某些东西,还是这种行为不一致?

解决方法

您看到的仍然是四舍五入,这不是您期望的四舍五入。 Python默认为rounds ties to even,而不是总是四舍五入,因为四舍五入关系会在数据中产生特定的偏差(四舍五入关系也是如此,但是这些偏差问题较少,因为它们不会影响整体分布)。

例如:

nums = [0.25,0.75]
[round(x,1) for x in nums]
# [0.2,0.8]

对于更多的小数点也是如此:

0.05,0.15

在上面的列表中包含import pathlib from pathlib import Path import os folderDir = Path(input("Please enter the parent directory: \n")) folderList = [folder for folder in folderDir.iterdir() if folder.is_dir()] for f in folderList: fileList = [e for e in f.iterdir() if e.is_file()] os.chdir(f) count = 1 for i in fileList: folderName = os.path.basename(os.path.dirname(i)) i.rename(folderName + "_" + str(count).zfill(3) + pathlib.Path(i).suffix) count += 1 …会产生令人惊讶的结果,因为这些十进制浮点值不能精确地表示为二进制浮点值,因此它们也不是偶数;例如,存储的0.5大约为0.05000000000000000278…,因此它不会四舍五入为(偶数)0.0,而是四舍五入为(奇数)0.1。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...