Skip to main content
 首页 » 编程设计

python之python中的 float 精度

2025年05月04日24lhb25

我有一个变量mn,它的值为 2.71989011072,我使用 python 的 round 函数来获得 2.720 的精度值,但我只得到 2.72

mn=2.71989011072 
print round(mn,3) 

给出 2.72 而不是 2.720

请您参考如下方法:

是的,print 函数应用了第二次舍入。

mn = 2.71989011072 
mn = round(mn, 3) 
print(mn) 

你会得到:

2.72 

您需要使用格式化字符串:

print("{0:.3f}".format(mn)) 

你会得到:

2.720 

请注意,格式化字符串可以为您进行四舍五入。 这样,您将获得相同的输出:

mn = 2.71989011072 
print("{0:.3f}".format(mn)) 
# => 2.720