繁体   English   中英

如何将浮点数打印到 n 个小数位,包括尾随 0?

[英]How to print float to n decimal places including trailing 0s?

即使结果有许多尾随 0,我也需要将浮点数打印或转换为 15 位小数位字符串,例如:

1.6 变成 1.6000000000000000

我试过 round(6.2,15) 但它返回 6.2000000000000002 添加一个舍入错误

我还在网上看到很多人将浮点数放入字符串中,然后手动添加尾随 0,但这似乎很糟糕......

做这个的最好方式是什么?

对于 2.6+ 和 3.x 中的 Python 版本

您可以使用str.format方法。 例子:

>>> print('{0:.16f}'.format(1.6))
1.6000000000000001

>>> print('{0:.15f}'.format(1.6))
1.600000000000000

注意1在第一实施例的端部被舍入误差; 这是因为十进制数 1.6 的精确表示需要无限数量的二进制数字。 由于浮点数的位数是有限的,因此该数字会四舍五入为附近但不相等的值。

对于 2.6 之前的 Python 版本(至少回到 2.0)

您可以使用“模格式”语法(这也适用于 Python 2.6 和 2.7):

>>> print '%.16f' % 1.6
1.6000000000000001

>>> print '%.15f' % 1.6
1.600000000000000

现代 Python >=3.6最简洁的方法是使用带有字符串格式的 f 字符串

>>> var = 1.6
>>> f"{var:.15f}"
'1.600000000000000'

浮点数缺乏将“1.6”精确表示到那么多小数位的精度。 舍入误差是真实的。 你的数字实际上不是 1.6。

查看: http : //docs.python.org/library/decimal.html

我想这本质上是把它放在一个字符串中,但这避免了舍入错误:

import decimal

def display(x):
    digits = 15
    temp = str(decimal.Decimal(str(x) + '0' * digits))
    return temp[:temp.find('.') + digits + 1]

我们可以使用format()在小数位后打印数字。 取自http://docs.python.org/tutorial/floatingpoint.html

>>> format(math.pi, '.12g')  # give 12 significant digits
'3.14159265359'

>>> format(math.pi, '.2f')   # give 2 digits after the point
'3.14'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM