python round用法_Python round 函数

round( number ) 函数会返回浮点数 number 的四舍五入值。

具体定义为 round(number[,digits]):如果 digits>0 ,四舍五入到指定的小数位;

如果 digits=0 ,四舍五入到最接近的整数;

如果 digits<0 ,则在小数点左侧进行四舍五入;

如果 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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值