int 向下取整
就是把数据类型转换为int型,传入类型错误会报错.
int('aa')
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'aa'
int(1.1)
1
int(1.5)
1
int(1.9)
1
int(-1.1)
-1
int(-1.5)
-1
int(-1.9)
-1
round()对数字进行四舍五入
基本用法round([数字或表达式],[参数]).参数为正整数,则对小数部分四舍五入,为0则对整数部分四舍五入,为负数则对整数部分四舍五入.可以把整个数字看做数轴,小数点是原点,整数部分代表负轴,小数部分代表正轴,参数的数字对应哪一位就对那一位上的数字四舍五入.
round(123.123,1)
123.1
round(123.123,2)
123.12
round(123.123,3)
123.123
round(123.567,1)
123.6
round(123.567,2)
123.57
round(123.567,3)
123.567
round(123.567,0)
124.0
round(123.123,-1)
120.0
round(125.123,-1)
130.0
round(125.123,-2)
100.0
math.ceil()对数字向上取整
这是源码的注释:
Return the ceiling of x as an Integral.
This is the smallest integer >= x. 大概意思是,处理后的数据大于等于本身即向上取整了
math.ceil(123.123)
124
math.ceil(0)
0
math.ceil(-123.123) # 负数比较有趣,要注意
-123
math.modf() 分别取小数部分和整数部分,返回的是元组
这是源码的注释:
== Return the fractional and integer parts of x.
Both results carry the sign of x and are floats.== 取出的两个数字都是浮点数.
但是小数部分会失去精度.对精度不高的可以用用,省事.不然的话还不如转成字符串用"."切割呢.说这个是想说,Python的标准库模块有很多对数据处理的方法,可以多去看看.
math.modf(-123.123)
(-0.12300000000000466, -123.0)
math.modf(0)
(0.0, 0.0)
math.modf(123.123)
(0.12300000000000466, 123.0)