python使用中会遇到几种取整的情况,现在整理一下,以供以后学习参考。
一、向上取整,所有小数都是向着数值更大的方向取整,不论正负。
math.ceil()
import math math.ceil(0.4) >>> 1 math.ceil(1.8) >>> 2 math.ceil(-1.8) >>> -1
二、向下取整,所有小数都是向着数值更小的方向取整,不论正负。
math.floor()
math.floor(1.8) >>> 1 math.floor(-1.8) >>> -2
三、四舍五入取整,对于round() 函数来说,当小数末尾为5时,如果前一位为奇数,取整为向绝对值更大的方向取整;当小数末尾的5前一位为偶数时,取整为去尾取整。
round()
round(1.2) >>> 1 round(1.6) >>> 2 # 当小数末尾为5时 round(1.5) >>> 2 round(3.5) >>> 4 round(-1.5) >>> -2 # 注意此时 round(2.5) >>> 2 round(4.5) >>> 4 round(-2.5) >>> -2
四、还有一种就是 int() 在格式转换时也经常用到,但int()取整为去尾取整,即不管小数后为多少,全部去掉,取整的方向总是让结果的绝对值比小数的绝对值更小。
int(-0.4) >>> 0 int(-1.6) >>> -1 int(0.7) >>> 0 int(2.6) >>> 2
五、还有一种 较为特殊的 “//” 整除运算符,其结果与向下取整相同。
9//2 >>> 4 9//4 >>> 2 9//5 >>> 1



