Python3数值取整的几种方法(向上取整,向下取整,四舍五入)

内置函数int(),向0取整。
内置函数round(),四舍五入取整。
math模块中的math.floor()向下取整,math.ceil()向上取整。

向上取整

1
2
3
4
5
6
>>> import math
>>> math.ceil(4.2)
5
>>> math.ceil(-4.8)
-4
>>>

向下取整

1
2
3
4
5
6
>>> import math
>>> math.floor(4.8)
4
>>> math.floor(-4.2)
-5
>>>

四舍五入

1
2
3
4
5
>>> round(-4.2)
-4
>>> round(4.8)
5
>>>

向0取整

1
2
3
4
5
>>> int(4.8)
4
>>> int(-4.2)
-4
>>>
大师兄 wechat
欢迎关注我的微信公众号:Python大师兄