使用步骤将小数点四舍五入到最低浮点数

round decimal to lowest float with steps

我正在尝试使用 python 中的步骤将小数舍入到最低浮点数。例如,如果步长为 0.01,则应将 0.287 四舍五入为 0.28,并保留 0.29。 问题是当我舍入 0.29 时我的函数打印 0.28:

int(0.29/0.01)*0.01

预先感谢您的帮助!

编辑:

我找到了解决这个问题的有效函数:

def round_best(a, step):
if abs(round(a/step)-(a/step))<0.00001:
    return round(a, -decimal.Decimal(str(step)).as_tuple().exponent)
else:
    return ((int(str(a/step).split('.')[0])) * step)

希望对您有所帮助!

步长为 0.01 -> 如果您的号码至少包含 2 位小数

number = 2.9
stab = 0.05
c = ((int(str(number/stab).split('.')[0])) * stab)
print(c)

终于可以用了