[Python] round函數

來源:互聯網
上載者:User

標籤:

在Python中,round函數對小數進行四捨五入的截斷。

然而:

>>> round(3.55, 1)3.5

官方文檔對於函數的解釋是:

Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.

>>> round(0.55, 1)0.6>>> round(3.55, 1)3.5
>>> from decimal import Decimal>>> Decimal(0.55)Decimal(‘0.5500000000000000444089209850062616169452667236328125‘)>>> Decimal(3.55)Decimal(‘3.54999999999999982236431605997495353221893310546875‘)

 

一種正確四捨五入的解決方案是用decimal模組實現:

from decimal import *number = ‘17.9555‘print Context(prec = len(number.split(‘.‘)[0]) + 3, rounding = ROUND_HALF_UP).create_decimal(number)

代碼裡加粗部分的解釋:

  1. number用字串表示,避免轉換為Decimal時,浮點數儲存產生的精度問題。
  2. prec:前面的len函數求的是整數部分的長度,後面的3是保留的小數位元。
  3. rounding:ROUND_HALF_UP表示四捨五入。

[Python] round函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.