在Python中,如何将float的精度降低到给定的步长?

In Python, how to reduce the precision of a float to a given step size?

我有一个可以具有任意精度的浮点数,并且指示这个数字的最小量的最小步长可以增加/减少:

num = 3.56891211101
min_step = 0.005

我想要一个函数,它接受这个 numstep_size 并将 num 舍入到给定的 min_step。所以在这种情况下,结果将是 3.570.

我试过这个:

num = 3.56891211101
min_step = 0.005

def myround(x, base):
    return base * round(x / base)

x = myround(num, min_step)
print(x)
>>> 3.5700000000000003

...很接近,但不完全是。我希望输出与 if:

相同
y = 3.570
print(y)
>>> 3.57

完成此任务的简单方法是什么?

我在 Python 3.8

我解决了它:

def myround(x, base):
    decimal_places = str(base)[::-1].find('.')
    precise = base * round(x / base)
    return round(precise, decimal_places)

x = myround(num, min_step)
print(x)
>>> 3.57

y = 3.570
print(y)
>>> 3.57

希望对其他人有所帮助。

大多数 Python 实现(包括 CPython 参考实现)使​​用 IEE 754 浮点数。因此,它们对于十进制值不准确。

规范的方式是使用十进制模块:

from decimal import Decimal, Context

num = 3.56891211101
c = Context(prec=3)
x= c.create_decimal(num)
print(x)

符合预期

3.57