說(shuō)說(shuō) Python 的 round 函數(shù)

round( number ) 函數(shù)會(huì)返回浮點(diǎn)數(shù) number 的四舍五入值。

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

  1. 如果 digits>0 ,四舍五入到指定的小數(shù)位;
  2. 如果 digits=0 ,四舍五入到最接近的整數(shù);
  3. 如果 digits<0 ,則在小數(shù)點(diǎn)左側(cè)進(jìn)行四舍五入;
  4. 如果 round() 函數(shù)只有 number 這個(gè)參數(shù),則等同于 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))

運(yùn)行結(jié)果:

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

注意: round(9.315,2)=9.31,并不是我們想的那樣!只有 9.315 后面還有數(shù)字,才會(huì)進(jìn)位,比如 round(9.3151,2)=9.32。

以上是 python3.x 的 round 函數(shù)說(shuō)明。

注意: python2.x 的 round 函數(shù)與 python 3.x 的 round 函數(shù)結(jié)果不同!

python2.x round 函數(shù)的官方定義為: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. 即如果舍入處理的值,離左右兩端相同距離,那么會(huì)遠(yuǎn)離 0,即為 1,所以 round(0.5)=1.0,而 round(-0.5)=-1。

python3.x round 函數(shù)的官方定義為:“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. 即如果舍入處理的值,離左右兩端相同距離,那么會(huì)朝向偶數(shù)方向處理,所以 round(0.5)=1.0,而 round(-0.5)=1,也是 1!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容