python are not allowed to carry rounding

python in rounding are not allowed to carry himself wrote a method
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 ))
 # if you want to achieve 0.2 shown as 0.20, may be used '% .2f'% num implemented 
Print (N7, ' = ' , ' % .2f ' % New_round (N7 / 100000000, 2))

result:

  -15355000 = -0.15

      -25000000 = -0.25

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

Guess you like

Origin www.cnblogs.com/snailgirl/p/11634990.html