python 中的浮点数精度

Floating point numbers precision in python

我有一个变量mn,其值为 2.71989011072,我使用 python 的舍入函数得到 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

函数将其四舍五入为前三位数字,正确结果为 2.72。零是打印 ans 字符串格式的问题,而不是四舍五入的问题。

要用三个零打印它,您需要执行以下操作:

print '{0:.3f}'.format(round(mn, 3))

这将首先舍入数字然后打印它,用三个零格式化它。

您需要数字的特定字符串表示,而不是其他数字。

使用format()代替round()

>>> mn = 2.71989011072
>>> format(mn, '.3f')
'2.720'

和python3,我们可以用f串

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

2.720