如何解决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。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。