Python取整及保留⼩数⼩结
1.int() 向下取整内置函数
1 n = 3.75
2 print(int(n))
>>> 3
3 n = 3.25
4 print(int(n))
>>> 3
1 n = 3.75
2 print(round(n))
>>> 4
3 n = 3.25
4 print(round(n))
>>> 3
3. floor() 向下取整 math模块函数
floor的英⽂释义:地板。顾名思义也是向下取整
1 import math
2 n = 3.75
python round函数怎么使用3 print(math.floor(n))
>>> 3
4 n = 3.25
5 print(math.floor(n))
>>> 3
ceil的英⽂释义:天花板。
1 import math
2 n = 3.75
3 il(n))
>>> 4
4 n = 3.25
5 il(n))
>>> 4
该⽅法返回⼀个包含⼩数部分和整数部分的元组
1 import math
2 n = 3.75
3 df(n))
>>> (0.75, 3.0)
4 n = 3.25
5 df(n))
>>> (0.25, 3.0)
6 n = 4.2
7 df(n))
(0.20000000000000018, 4.0)
最后⼀个的输出,涉及到了另⼀个问题,即浮点数在计算机中的表⽰,在计算机中是⽆法精确的表⽰⼩数的,⾄少⽬前的计算机做不到这⼀点。上例中最后的输出结果只是 0.2 在计算中的近似表⽰。Python 和 C ⼀样, 采⽤ IEEE 754 规范来存储浮点数。
6.保留⼀位⼩数
三种⽅法:
1 print(round(10/3,1))
2 print('%.1f'%(10/3))
3 print(format((10/3),'.1f'))
>>> 3.3