试着探讨python2.7和python3.6中的round函数,numpy的around函数等多种实现四舍五入的方法尝试和各自缺陷,并不对深层次的原理进行解释。
# 保留个位数
>>> round(0.5)
1.0
>>> round(1.5)
2.0
>>> round(2.5)
3.0
# 保留十位数
>>> round(105, -1)
110.0
>>> round(115, -1)
120.0
>>> round(125, -1)
130.0
>>> round(0.05, 1)
0.1
>>> round(0.15, 1)
0.1
>>> round(0.25, 1)
0.3
>>> round(0.35, 1)
0.3
# 在奇数不进位,只有在偶数才进位
# 5均不进位
>>> round(0.5)
0
>>> round(1.5)
2
>>> round(2.5)
2
>>> round(3.5)
4
# 奇数进位
>>> round(105, -1)
100
>>> round(115, -1)
120
>>> round(125, -1)
120
>>> round(135, -1)
140
>>> round(104, -1)
100
>>> round(106, -1)
110
>>> round(116, -1)
120
# 5均不进位
>>> round(0.06, 1)
0.1
>>> round(0.07, 1)
0.1
>>> round(0.15, 1)
0.1
>>> round(0.16, 1)
0.2
>>> round(0.25, 1)
0.2
>>> round(0.26, 1)
0.3
>>> '%.1f'%(0.15)
'0.1'
>>> '%.1f'%(0.25)
'0.2'
>>> '%.1f'%(0.16)
'0.2'
>>> '%.1f'%(0.26)
'0.3'
# 5不进位,6才进位
>>> import numpy as np
>>>
>>> np.around(0.5)
0.0
>>> np.around(1.5)
2.0
# 依然无法实现正常四舍五入
参考链接: