问题描述
我需要将浮点数打印或转换为小数点后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
我尝试了舍入(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...
做到这一点的最佳方法是什么?
What is the best way to do this?
推荐答案
适用于2.6+和3.x版的Python版本
您可以使用 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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!