python中关于round函数的小坑 - _小苹果 - 博客园www.cnblogs.com
同样的坑:整数a/100 不等于a×0.01
在python2.7的doc中,round()的最后写着,“Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0.”
保留值将保留到离上一位更近的一端(四舍六入),如果距离两端一样远,则保留到离0远的一边。所以round(0.5)会近似到1,而round(-0.5)会近似到-1。
但是到了python3.5的doc中,文档变成了“values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice.”
如果距离两边一样远,会保留到偶数的一边。比如round(0.5)和round(-0.5)都会保留到0,而round(1.5)会保留到2。
所以如果有项目是从py2迁移到py3的,可要注意一下round的地方(当然,还要注意/和//,还有print,还有一些比较另类的库)。
参考了一下文档,试过多种就解决办法:
1,试过高精度包 decimal, (没有成功的将 12.5 变成13)
decimal.Decimal('2.5').quantize(decimal.Decimal('1'),rounding=decimal.ROUND_HALF_UP)9.4. decimal - Decimal fixed point and floating point arithmetic - Python 3.6.5 documentationdocs.python.org
2,更改getcontext().rounding = ROUND_HALF_UP (默认值为ROUND_HALF_EVEN)
3, python这个小细节在结算业务确实挺吓人,我还是手写取整函数吧:
import math
def round_five_up(self, dit):
""":param dit: 取整的浮点数:return:"""
(point_d, int_d) = math.modf(dit)
print(point_d)
if int_d > 0 and point_d >= 0.5:
return int(int_d) + 1
if int_d < 0 and point_d <= -0.5:
return int(int_d) - 1
return int(int_d)