python function to set accuracy of float

2019-07-12 17:36发布

问题:

I would like to make a function:

def accuracy(number, index):

For example

  • accuracy(2.5e-10, -5) would return 0.
  • accuracy(49, 2) would return 0.
  • accuracy(50, 2) would return 100.

    So basically it would round to the closest 10 power of the index index How would you do that?

回答1:

def accuracy(n, i):
    return round(float(n) / 10**i) * 10**i