'Python: How to find closest rounded number to a given value with certain properties?

  • You are given a variable num with a value greater than 0.
  • You need to find the closest number to num that can be expressed as 1*10**n, 2*10**n or 5*10**n (n can be any integer including 0 and negative numbers)

This is my attempt at solving this:

num = 1
if num < 1:
    num_scale, i = 0, 0
    # "f'{num:.20f}'" shows for example: 0.00003 instead of 3e-5
    while f'{num:.20f}'[i] in "0.":
        if f'{num:.20f}'[i] == "0":
            num_scale += 1
        i += 1
    num_scale = -num_scale + 1
else:
    num_scale = len(str(int(num))) - 1

closest_list = [abs((i * (10 ** num_scale)) - num) for i in [1, 2, 5, 10]]
closest = [1, 2, 5, 10][optional_num1s.index(min(optional_num1s))] * 10 ** num_scale

But my code doesn't work for numbers below 1, it always gives that the closest number is 1 * 10 ** num_scale even when its not true so can you find my mistake?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source