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']