Python教程:ceil、floor、round、int取整 |
您所在的位置:网站首页 › python浮点数如何取整 › Python教程:ceil、floor、round、int取整 |
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.四舍五入 roundround() 方法返回浮点数的四舍五入值。 使用语法: 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.取整 intint() 向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 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |