久久久久久久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 的意思不同)
主站蜘蛛池模板: 91精品国产色综合久久不卡蜜臀 | 一区二区三区欧美在线观看 | 一区二区三区四区电影视频在线观看 | 中文字幕国产视频 | 日本高清精品 | www.99热.com| 美女福利网站 | 天天操妹子 | 日韩成人精品 | 国久久 | 91国产精品在线 | 激情婷婷成人 | 在线āv视频 | 性高湖久久久久久久久aaaaa | 天天干天天操天天射 | 日本三级电影在线看 | 国产精品小视频在线观看 | 在线一区视频 | 久久中文免费视频 | 久久男人 | 四虎永久| 免费黄色网址视频 | 亚洲一区二区三区免费在线观看 | 美女艹b | 欧美日本一区 | 91大神新作在线观看 | 超级碰在线 | 国产三级大片 | 天堂成人国产精品一区 | 国产一区二区电影 | 精品欧美一区二区三区久久久 | 亚洲一区二区三区免费观看 | 亚洲视频一区 | 操视频网站 | 久久久久久高清 | 在线一级片 | 特级黄一级播放 | 三级在线观看 | 91大神在线资源观看无广告 | 久久国产成人精品国产成人亚洲 | 国产一区二区视频在线观看 |