心在远方

导航

python中的取整

处理数据时,经常会遇到取整的问题,现总结如下

1,向下取整 int()

1 >>>a = 3.1
2 >>>b = 3.7
3 >>>int(a)
3
4 >>>int(b)
3
5 >>>int(-a)
-3
6 >>>int(-b)
-3

2,向上取整 math.ceil()

 1 >>>from math import ceil
 2 >>>a = 3.1
 3 >>>b = 3.7
 4 >>>ceil(a)
 5 4
 6 >>>ceil(b)
 7 4
 8 >>>ceil(-a)
 9 -3
10 >>>ceil(-b)
11 -3

3,四舍五入 round()

 1 >>>a = 3.123
 2 >>>b = 3.256
 3 >>>round(a)
 4 3.0
 5 >>>round(a, 2)
 6 3.12
 7 >>>round(b, 2)
 8 3.26
 9 >>>round(b, 1)
10 3.3

 

posted on 2018-04-02 22:32  韩伟123  阅读(4404)  评论(0)    收藏  举报