说说 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!

发布了677 篇原创文章 · 获赞 777 · 访问量 100万+

猜你喜欢

转载自blog.csdn.net/deniro_li/article/details/105464516