久久久久久久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 的意思不同)
主站蜘蛛池模板: 亚洲二区在线 | 久久成人久久 | 手机看片1| 国产亚洲一区二区三区在线观看 | 超碰在线播| 国产成人精品午夜视频免费 | 国产亚洲欧美在线视频 | 国产一区二区在线免费视频 | 日韩一区二区在线视频 | 久久草视频 | 国产欧美精品区一区二区三区 | jlzzxxxx18hd护士| 亚洲精品3 | 成人精品在线视频 | 亚洲精品亚洲人成人网 | 91在线一区| 国产精品18久久久久久白浆动漫 | 国产精品欧美日韩 | 国产精品人人做人人爽 | 伊人网91 | 男女羞羞视频网站 | 国产真实精品久久二三区 | 日本成人福利 | 国产成人在线看 | www.99热这里只有精品 | 一区二区在线免费观看 | 在线中文视频 | 久久久女| 日韩亚洲欧美综合 | 国产午夜精品视频 | 亚洲欧美国产毛片在线 | 久草网址 | 日韩在线视频播放 | av在线播放不卡 | 一区二区精品电影 | 激情一区二区三区 | 亚洲国产一区二区三区, | 国产精品视频免费播放 | 国产精品大全 | 国产免费一区二区三区网站免费 | 国产精品日韩欧美一区二区 |