python 人数取整_避免PYTHON取整四舍六入五成双问题

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 documentation​docs.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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值