round( number ) 函數(shù)會(huì)返回浮點(diǎn)數(shù) number 的四舍五入值。
具體定義為 round(number[,digits]):
- 如果 digits>0 ,四舍五入到指定的小數(shù)位;
- 如果 digits=0 ,四舍五入到最接近的整數(shù);
- 如果 digits<0 ,則在小數(shù)點(diǎn)左側(cè)進(jìn)行四舍五入;
- 如果 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!