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.四舍五入 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取整,取整方向总是让结果比小数的绝对值更小。

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

参考链接:Python取整——向上取整、向下取整、四舍五入取整、向0取整

posted @   Hider1214  阅读(955)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示