以 0.05 为增量向上舍入
Rounding up in 0.05 increments
我希望以最接近的 0.05 为增量进行四舍五入。例如,如果我有一个数字 1.01,它必须四舍五入到 1.05。是否有任何 python 库可用于执行此操作?
我会通过以下方式解决这个问题:
import math
a = 1.01
b = a*20
c = math.ceil(b)
d = c/20
print(d)
我知道四舍五入到最接近的整数值很容易,所以我转换了我的数字,而不是递增 0.05
我想递增 1
。这是通过乘以 20(如 0.05*20=1
)来完成的。然后我可以将 20x
较高的数字四舍五入到最接近的整数,然后除以 20 得到我要查找的结果。
另请注意 math
包含在 Python 中,因此无需下载新模块!
你可以这样做:
import math
def round_by_05(num):
check_num = num * 20
check_num = math.ceil(check_num)
return check_num / 20
这给出:
>>> round_by_05(1.01)
1.05
>>> round_by_05(1.101)
1.15
通用解决方案(不需要 math.ceil()
)
def round_to_next(val, step):
return val - (val % step) + (step if val % step != 0 else 0)
给出:
>>> round_to_next(1.04, 0.05)
1.05
>>> round_to_next(1.06, 0.05)
1.1
>>> round_to_next(1.0, 0.05)
1.0
我希望以最接近的 0.05 为增量进行四舍五入。例如,如果我有一个数字 1.01,它必须四舍五入到 1.05。是否有任何 python 库可用于执行此操作?
我会通过以下方式解决这个问题:
import math
a = 1.01
b = a*20
c = math.ceil(b)
d = c/20
print(d)
我知道四舍五入到最接近的整数值很容易,所以我转换了我的数字,而不是递增 0.05
我想递增 1
。这是通过乘以 20(如 0.05*20=1
)来完成的。然后我可以将 20x
较高的数字四舍五入到最接近的整数,然后除以 20 得到我要查找的结果。
另请注意 math
包含在 Python 中,因此无需下载新模块!
你可以这样做:
import math
def round_by_05(num):
check_num = num * 20
check_num = math.ceil(check_num)
return check_num / 20
这给出:
>>> round_by_05(1.01)
1.05
>>> round_by_05(1.101)
1.15
通用解决方案(不需要 math.ceil()
)
def round_to_next(val, step):
return val - (val % step) + (step if val % step != 0 else 0)
给出:
>>> round_to_next(1.04, 0.05)
1.05
>>> round_to_next(1.06, 0.05)
1.1
>>> round_to_next(1.0, 0.05)
1.0