1.向上取整 math.ceil
math.ceil() 严酷遵循向上取整,全部小数都向着数值更大的方向取整。- import math
- math.ceil(-1.5) # -1
- math.ceil(1.5) # 2
- math.ceil(-0.9) # 0
复制代码 2.向下取整 math.floor
同 math.ceil 类似,方向相反,向下取整。- import math
- math.floor(-0.5) # -1
- math.floor(1.6) # 1
复制代码 3.四舍五入 round
round() 方法返回浮点数的四舍五入值。
使用语法:- round(x, [, n])
- x -- 浮点数
- n -- 小数点位数
复制代码 实操:- round(1.5) # 2
- round(-1.5) # -2
- round(-0.5) # 0
- round(0.5) # 0
- round(2.5) # 2
- round(100.5132, 2) # 100.51
复制代码 不传第二个参数时,默认取整,四舍五入
小数末端为5的处理方法:
- 末端为5的前一位为奇数:向绝对值更大的方向取整
- 末端为5的前一位为偶数:去尾取整
round只是针对小数点后.5的环境会按照规律盘算,因为存储时不同,例如:4.5存储时为4.4999999...
4.取整 int
int() 向0取整,取整方向总是让结果比小数的绝对值更小。- #Python学习交流群:725638078
- int(-0.5) # 0
- int(-0.9) # 0
- int(0.5) # 0
- int(1.9) # 1
复制代码 5.整除 //
”整除取整“符号运算实现向下取整,与 math.floor() 方法效果一样。- -1 // 2 # -1
- -3 // 2 # -2
- 101 // 2 # 50
- 3 // 2 # 1
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |