說說 Python 的 round 函數

round( number ) 函數會返回浮點數 number 的四捨五入值。

具體定義爲 round(number[,digits]):

  1. 如果 digits>0 ,四捨五入到指定的小數位;
  2. 如果 digits=0 ,四捨五入到最接近的整數;
  3. 如果 digits<0 ,則在小數點左側進行四捨五入;
  4. 如果 round() 函數只有 number 這個參數,則等同於 digits=0。

示例如下:

logging.info(round(9.315,2))
logging.info(round(9.3151,2))
logging.info(round(9.316,2))
logging.info(round(9.316,-1))

運行結果:

INFO - 9.31
INFO - 9.32
INFO - 9.32
INFO - 10.0

注意: round(9.315,2)=9.31,並不是我們想的那樣!只有 9.315 後面還有數字,纔會進位,比如 round(9.3151,2)=9.32。

以上是 python3.x 的 round 函數說明。

注意: python2.x 的 round 函數與 python 3.x 的 round 函數結果不同!

python2.x round 函數的官方定義爲:Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0. 即如果舍入處理的值,離左右兩端相同距離,那麼會遠離 0,即爲 1,所以 round(0.5)=1.0,而 round(-0.5)=-1。

python3.x 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. 即如果舍入處理的值,離左右兩端相同距離,那麼會朝向偶數方向處理,所以 round(0.5)=1.0,而 round(-0.5)=1,也是 1!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章