Python內建函數(55)——round

來源:互聯網
上載者:User

標籤:1.0   min   support   bsp   amp   ber   整數   cal   expec   

英文文檔:

round(number[, ndigits])
Return the floating point value number rounded to ndigits digits after the decimal point. If ndigits is omitted, it returns the nearest integer to its input. Delegates to number.__round__(ndigits).
For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). The return value is an integer if called with one argument, otherwise of the same type as number.
Note:

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

 

說明:

  1. round函數用於對浮點數進行四捨五入求值,具體保留幾位小數,以傳入的ndigits參數來控制。

>>> round(1.1314926,1)1.1>>> round(1.1314926,5)1.13149

  2. ndigits參數為選擇性參數,當不傳入時,即以預設保留0位小數進行取整,返回的是整數。

>>> round(1.1314926)1

  3. ndigits參數傳入0時,雖然與不傳入ndigits參數一樣保留0位小數進行四捨五入,但是返回的值是浮點型。

>>> round(1.1314926,0)1.0

  4. ndigits參數小於0時,對整數部分進行四捨五入,ndigits參數控制了對浮點數的整數部分的後幾位進行四捨五入,小數部分全部清0,傳回型別是浮點數。如果傳入的浮點數的整數部分位元小於ndigits參數絕對值,則返回0.0.

>>> round(11314.926,-1)11310.0>>> round(11314.926,-3)11000.0>>> round(11314.926,-4)10000.0>>> round(11314.926,-5)0.0

  5. round四捨五入時是遵循靠近0原則,所以-0.5和0.5進行0位四捨五入,返回的都是0.

>>> round(0.5)0>>> round(-0.5)0

  6. 對於浮點數求四捨五入有一個陷阱,有些四捨五入結果不像預期那樣,比如round(2.675, 2) 的結果是2.67 而不是預期的 2.68,這不是bug,而是浮點數在儲存的時候因為位元有限,實際儲存的值和顯示的值有一定誤差。

>>> round(2.675, 2)2.67

  7. 對整數也能進行round操作,傳回值也是整形。

>>> round(134567)134567>>> round(134567,0)134567>>> round(134567,1)134567>>> round(134567,2)134567>>> round(134567,-2)134600>>> round(134567,-6)0

 

Python內建函數(55)——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.