1.int()向下取整 内置函数
1 n = 3.75
2 print(int(n))
>>> 3
2.round() 四舍五入 内置函数
1 n = 3.75
2 print(round(n))
>>> 4
3.floor() 向下取整 math模块函数
1 import math
2 n = 3.75
3 print(math.floor(n))
>>> 3
4.ceil()向上取整 math模块函数
1 n = 3.25
2 print(math.ceil(n))
>>> 4
5.modf() 分别取整数部分和小数部分 math模块函数
1 import math
2 n = 3.75
3 print(math.modf(n))
>>> (0.75, 3.0)
6.保留?位小数
1 print(round(10/3,1))
2 print('%.1f'%(10/3))
3 print(format((10/3),'.1f'))
>>> 3.3
本文深入探讨了Python中处理数值的多种方法,包括使用内置函数int()进行向下取整,round()进行四舍五入,以及math模块中的floor()、ceil()、modf()等函数的详细应用。此外,还介绍了如何通过不同方式保留小数位数。
1万+

被折叠的 条评论
为什么被折叠?



