在Python中将数字舍入为特定值

时间:2016-05-16 07:22:32

标签: python decimal rounding

我想在python舍入到指定值。圆形或.99,9.99或其他值。价值可以通过动态。 例如:

回到.99

20.11 => 20.99
11.33 = 11.99
1.00 = 1.99

圆满至9.99

100 => 109.99
293.33 => 299.99

圆满至0.33

1 => 1.33
34.44 => 35.33

怎么做?

1 个答案:

答案 0 :(得分:3)

def roundAprox(a, b):
    c = 0
    while (pow(10, c) < b):
        c += 1

    result = int(a)
    return result - result % (pow(10, c)) + b

让我们测试一下:

print roundAprox(20.11, 0.99)
print roundAprox(11.33, 0.99)
print roundAprox(1.00, 0.99)
print roundAprox(100, 9.99)
print roundAprox(293.33, 9.99)
print roundAprox(1, 0.33)
print roundAprox(34.44, 0.33)

结果:

20.99
11.99
1.99
109.99
299.99
1.33
34.33

我认为上一轮到0.33是错误的,你希望34.44成为34.33

相关问题