Python - Round to nearest 05

后端 未结 9 1955
死守一世寂寞
死守一世寂寞 2020-11-29 08:14

Hvor can I en python do the following rounding:

Round to the nearest 05 decimal

7,97 -> 7,95

6,72 -> 6,70

31,06 -> 31,05

36,04 -> 36,

9条回答
  •  余生分开走
    2020-11-29 08:56

    I faced the same problem and as I didn't find the ultimate solution to this, here's mine.

    Firs of all the main part(which was answered before):

    def round_to_precision(x, precision):
        # This correction required due to float errors and aims to avoid cases like:
        # 100.00501 / 0.00001 = 10000500.999999998
        # It has a downside as well - it may lead to vanishing the difference for case like
        # price = 100.5 - (correction - correction/10), precision = 1 => 101 not 100
        # 5 decimals below desired precision looks safe enough to ignore
        correction = 1e-5 if x > 0 else -1e-5
        result = round(x / precision + correction) * precision
        return round(result, find_first_meaningful_decimal(precision))
    

    The only tricky part here was that find_first_meaningful_decimal, which I've implemented like this:

    def find_first_meaningful_decimal(x):
        candidate = 0
        MAX_DECIMAL = 10
        EPSILON = 1 / 10 ** MAX_DECIMAL
        while round(x, candidate) < EPSILON:
            candidate +=1
            if candidate > MAX_DECIMAL:
                raise Exception('Number is too small: {}'.format(x))
        if int(x * 10 ** (candidate + 1)) == 5:
            candidate += 1
        return candidate
    
    
    print(round_to_precision(129.950002, 0.0005))
    print(round_to_precision(-129.95005, 0.0001))
    
    129.9505
    -129.9501
    

提交回复
热议问题