Python rounding a floating point number to nearest 0.05

You can round down to the nearest multiple of a like this:

def round_down(x, a):
    return math.floor(x / a) * a

You can round to the nearest multiple of a like this:

def round_nearest(x, a):
    return round(x / a) * a

As @Anonymous wrote:

You can round to the nearest multiple of a like this:

def round_nearest(x, a):
    return round(x / a) * a

Works nearly perfectly, but round_nearest(1.39, 0.05) gives 1.4000000000000001. To avoid it I'll recommend to do:

import math
def round_nearest(x, a):
    return round(round(x / a) * a, -int(math.floor(math.log10(a))))

Which rounds to precision a, and then to number of significant digits, that has your precision a

Tags:

Python