Don Coder
Don Coder

Reputation: 556

How to find n decimal of a value?

I'm trying to divide a number to n decimals.

For example

def find_digit(number, n):
    return pow(number, n)
    # this should return 0.0005

n = 5
number = 4
print(find_digit(number, n))

1024

My expected value is 0.0005 and now I'm sure it is not the power of a value but I can not remember how to calculate this.

Upvotes: 0

Views: 44

Answers (2)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48437

You should change the logic from find_digit method.

0.0005 is equals to 5 / (10 ^ 4)

def find_digit(number, n):
     return number / pow(10, n)
print(find_digit(number, n))

Output

>> 0.0005

Upvotes: 4

Baurin Leza
Baurin Leza

Reputation: 2094

maybe less pythonic:

def find_digit(number, n):
    return number*pow(10, -n)

print (find_digit(number=5, n=4))

Output:

>>>0.0005

Upvotes: 0

Related Questions