[Python] Python round a float to nearest 0.05 or to multiple of another float

Discussão em 'Python' iniciado por Stack, Agosto 14, 2025.

  1. Stack

    Stack Membro Participativo

    I want to emulate this function. I want to round a floating point number down to the nearest multiple of 0.05 (or generally to the nearest multiple of anything).

    I want this:

    >>> round_nearest(1.29, 0.05)
    1.25

    >>> round_nearest(1.30, 0.05)
    1.30


    I can do this:

    import math

    def round_nearest(n, r):
    return n - math.fmod(n, r)

    >>> round_nearest(1.27, 0.05)
    1.25 # Correct!

    >>> round_nearest(1.30, 0.05)
    1.25 # Incorrect! Correct would be 1.30.


    The incorrect answer above is presumably due to floating point rounding. I could put some special case check to see if the n is "close enough" to a multiple of r and not do the subtraction, and that would probably work, but is there a better way? Or is this strategy the best option?

    Continue reading...

Compartilhe esta Página