Python取整及保留小数
Tags: Python
基础
1.int() 向下取整 内置函数
1 2 3 4 | n = 3.75 print(int(n))>>> 3 n = 3.25 print(int(n))>>> 3 |
2.round() 四舍五入 内置函数
1 2 3 4 5 6 7 | n = 3.75 print(round(n))>>> 4 n = 3.25 print(round(n))>>> 3 >>> print(round(2.5)) 2 |
3. floor() 向下取整 math模块函数
floor的英文释义:地板。顾名思义也是向下取整
1 2 3 4 5 | import math n = 3.75 print(math.floor(n))>>> 3 n = 3.25 print(math.floor(n))>>> 3 |
4.ceil()向上取整 math模块函数
ceil的英文释义:天花板。
1 2 3 4 5 | import math n = 3.75 print(math.ceil(n))>>> 4 n = 3.25 print(math.ceil(n))>>> 4 |
5.modf() 分别取整数部分和小数部分 math模块函数
该方法返回一个包含小数部分和整数部分的元组
1 2 3 4 5 6 7 | import math n = 3.75 print(math.modf(n))>>> (0.75, 3.0) n = 3.25 print(math.modf(n))>>> (0.25, 3.0) n = 4.2 print(math.modf(n))(0.20000000000000018, 4.0) |
最后一个的输出,涉及到了另一个问题,即浮点数在计算机中的表示,在计算机中是无法精确的表示小数的,至少目前的计算机做不到这一点。上例中最后的输出结果只是 0.2 在计算中的近似表示。Python 和 C 一样, 采用 IEEE 754 规范来存储浮点数。
6.保留一位小数
三种方法:
1 2 3 | print(round(10/3,1)) print('%.1f'%(10/3)) print(format((10/3),'.1f'))>>> 3.3 |
综合示例
写出一个程序,接受一个正浮点数值,输出该数值的近似整数值。如果小数点后数值大于等于5,向上取整;小于5,则向下取整。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import math a = math.modf(float(input())) if a[0]>=0.5: print(int(a[1]+1)) else: print(int(a[1])) -- 或者 num = input() l = num.split('.') if float('0'+'.'+l[1]) >= 0.5 : r = int(l[0]) + 1 else: r = l[0] print(r) |