我希望以最接近的 0.05 为增量进行四舍五入。例如,如果我有一个数字 1.01,它必须四舍五入到 1.05。有没有可用于执行此操作的 Python 库?
请您参考如下方法:
通用解决方案(不需要 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
