编程语言
首页 > 编程语言> > python 四舍五入进位不准

python 四舍五入进位不准

作者:互联网

python中四舍五入进位不准,自己写了个方法
n = -15355000
n1 = -25000000
n2 = -35500000
n3 = 45300000
n4 = 55000000
n5 = 65500000
n6 = 7500000
n7 = 60000000

def new_round(_float, _len):
    if str(_float).startswith('-') and len(str(_float)) == _len + 3:
        return round(_float, _len)
    elif len(str(_float)) == _len + 2:
        return round(_float, _len)
    elif str(_float)[-1] == '5':
        return (round(float(str(_float)[:-1] + '6'), _len))
    else:
        return (round(_float, _len))
print(n , '=', new_round(n/100000000, 2))
print(n1, '=', new_round(n1/100000000, 2))
print(n2, '=', new_round(n2/100000000, 2))
print(n3, '=', new_round(n3/100000000, 2))
print(n4, '=', new_round(n4/100000000, 2))
print(n5, '=', new_round(n5/100000000, 2))
print(n6, '=', new_round(n6/100000000, 2))
# 如果想实现 0.2 显示为 0.20,可使用 '%.2f' % num 实现
print(n7, '=', '%.2f' % new_round(n7/100000000, 2))

结果:

  -15355000 = -0.15

      -25000000 = -0.25

      -35500000 = -0.36
      45300000 = 0.45
      55000000 = 0.55
      65500000 = 0.66
      7500000 = 0.08
      60000000 = 0.60

标签:四舍五入,python,float,len,100000000,print,new,round,进位
来源: https://www.cnblogs.com/snailgirl/p/11634990.html