問題描述
我需要將浮點數打印或轉換為小數點后 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?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!