将数字舍入到 Python 中的特定值
Rounding numbers to a specific value in Python
我想在python中四舍五入到指定的值。四舍五入到小费或 0.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
怎么做?
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
我想在python中四舍五入到指定的值。四舍五入到小费或 0.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
怎么做?
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