如何将浮点数打印到 n 位小数,包括尾随 0? [英] How to print float to n decimal places including trailing 0s?

查看:19
本文介绍了如何将浮点数打印到 n 位小数,包括尾随 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to print or convert a float number to 15 decimal place string even if the result has many trailing 0s eg:

1.6 变成 1.6000000000000000

1.6 becomes 1.6000000000000000

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

I tried round(6.2,15) but it returns 6.2000000000000002 adding a rounding error

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

I also saw various people online who put the float into a string and then added trailing 0's manually but that seems bad...

最好的方法是什么?

推荐答案

适用于 Python 2.6+ 和 3.x 版本

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

For Python versions in 2.6+ and 3.x

You can use the str.format method. Examples:

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

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

注意第一个例子末尾的 1 是舍入错误;发生这种情况是因为十进制数 1.6 的精确表示需要无限个二进制数字.由于浮点数的位数是有限的,因此该数字会四舍五入到一个附近但不相等的值.

Note the 1 at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.

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

You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):

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

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

这篇关于如何将浮点数打印到 n 位小数,包括尾随 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆