1、取整处理函数
1.int() 向下取整 内置函数 spa
1 n = 3.75 2 print(int(n))
>>> 3 3 n = 3.25 4 print(int(n))
>>> 3
2.round() 四舍五入 内置函数code
1 n = 3.75 2 print(round(n))
>>> 4 3 n = 3.25 4 print(round(n))
>>> 3
3. floor() 向下取整 math模块函数 blog
floor的英文释义:地板。顾名思义也是向下取整utf-8
1 import math 2 n = 3.75 3 print(math.floor(n))
>>> 3 4 n = 3.25 5 print(math.floor(n))
>>> 3
4.ceil()向上取整 math模块函数it
ceil的英文释义:天花板。class
1 import math 2 n = 3.75 3 print(math.ceil(n))
>>> 4 4 n = 3.25 5 print(math.ceil(n))
>>> 4
5.modf() 分别取整数部分和小数部分 math模块函数import
该方法返回一个包含小数部分和整数部分的元组
1 import math 2 n = 3.75 3 print(math.modf(n))
>>> (0.75, 3.0) 4 n = 3.25 5 print(math.modf(n))
>>> (0.25, 3.0) 6 n = 4.2 7 print(math.modf(n))
(0.20000000000000018, 4.0)
最后一个的输出,涉及到了另外一个问题,即浮点数在计算机中的表示,在计算机中是没法精确的表示小数的,至少目前的计算机作不到这一点。上例中最后的输出结果只是 0.2 在计算中的近似表示。Python 和 C 同样, 采用 IEEE 754 规范来存储浮点数。coding
2、小数处理方法
1.数据精度处理,保留小数位数
(1)%f四舍五入方法 ---> "%.2f"
a = 1.23456 print ('%.4f' % a) print ('%.3f' % a) print ('%.2f' % a) ----->1.2346 ----->1.235 ----->1.23
(2)不四舍五入
#coding=utf-8 a = 12.345 print str(a).split('.')[0] + '.' + str(a).split('.')[1][:2] ----> '12.34'
import re a = 12.345 print re.findall(r"\d{1,}?\.\d{2}", str(a)) ---->['12.34']