久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

如何將浮點數打印到 n 位小數,包括尾隨 0?

How to print float to n decimal places including trailing 0s?(如何將浮點數打印到 n 位小數,包括尾隨 0?)
本文介紹了如何將浮點數打印到 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?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Python 3 Float Decimal Points/Precision(Python 3 浮點小數點/精度)
Converting Float to Dollars and Cents(將浮點數轉換為美元和美分)
What are some possible calculations with numpy or scipy that can return a NaN?(numpy 或 scipy 有哪些可能的計算可以返回 NaN?)
Python float to ratio(Python浮動比率)
How to manage division of huge numbers in Python?(如何在 Python 中管理大量數字的除法?)
mean from pandas and numpy differ(pandas 和 numpy 的意思不同)
主站蜘蛛池模板: 免费a级毛片在线播放 | 日本免费小视频 | 美国一级黄色片 | 色五月激情五月 | 在线日韩 | 2021天天躁夜夜看 | 一区二区三区四区在线视频 | 97视频人人澡人人爽 | 一区二区福利视频 | 国产成人久久精品 | 国产福利视频 | 国产精品一区一区三区 | 国产高清免费视频 | 精品中文字幕一区 | 玖玖国产精品视频 | www.五月天婷婷 | 日韩欧美国产精品一区 | 日韩毛片网 | 99久久99| 亚州春色 | 美女日批免费视频 | 91久久精品日日躁夜夜躁国产 | 日本中文字幕在线观看 | 日韩精品中文字幕一区二区三区 | 国产区在线看 | 日韩精品一区二区三区视频播放 | 久草热视频 | 国产精品久久国产精品 | 午夜精品久久久久久久久久久久久 | 亚洲色综合 | 国产成人精品免费 | 一级国产精品一级国产精品片 | а√中文在线8 | 久久精品日| 国产超碰人人爽人人做人人爱 | 精品真实国产乱文在线 | 精品91久久 | 成人特级毛片 | 99热国产免费 | 在线日韩福利 | 色毛片 |