[Python]round四捨五入精度缺失的解決

來源:互聯網
上載者:User
文章目錄
  • 現象:
  • google中有人這麼解決的:
  • 現在使用的方式是:

環境:

os: win7 64bit

       python:2.7.5  32bit

      

對python四捨五入的解決方案現象:一般的四捨五入操作都是使用內建的round方法
In [14]: round(2.675,2)Out[14]: 2.67
文檔中這樣解釋的The documentation for the built-in
round() function says that it rounds to the nearest value, rounding ties away from zero. Since the decimal fraction 2.675 is exactly halfway
between 2.67 and 2.68, you might expect the result here to be (a binary approximation to) 2.68. It’s not, because when the decimal string
2.675 is converted to a binary floating-point number, it’s again replaced with a binary approximation, whose exact value is
In [22]: Decimal(2.675)Out[22]: Decimal('2.67499999999999982236431605997495353221893310546875')

所以對於精度有明確要求的數學計算來說,使用round是不行的google中有人這麼解決的:

>>> from decimal import Decimal>>> n = Decimal('1.555')>>> round(n, 2)Decimal('1.56')

##但是這個方法在2.7.5中已經不再適用了 現在使用的方式是:可以使用str.format來格式化數字實現四捨五入

 from decimal import DecimalIn [15]: '{:.2f}'.format(Decimal('2.675'))Out[15]: '2.68''

錯誤的寫法

In [12]: '{:.2f}'.format(2.675)Out[12]: '2.67'

In [13]: '{:.2f}'.format('2.675')---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)

In [14]: '{:.2f}'.format(Decimal(2.675))Out[14]: '2.67'

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.