Find the number of digits after the decimal point

Question:

I’m trying to write a Python 2.5.4 code to write a function that takes a floating-point number x as input and returns the number of digits after the decimal point in x.

Here’s my code:

def number_of_digits_post_decimal(x):
    count = 0
    residue = x -int(x)
    if residue != 0:
        multiplier = 1
        while int(multiplier * residue) != (multiplier * residue):
            count += 1
            multiplier = 10 * multiplier
            print count
            print multiplier
            print multiplier * residue
            print int(multiplier * residue)
            return count

print number_of_digits_post_decimal(3.14159)

The print statements within the while loop are only for debugging purposes.

Now when I run this code, I get the following as output.

1

10

1.4159

1

2

100

14.159

14

3

1000

141.59

141

4

10000

1415.9

1415

5

100000

14159.0

14158

6

1000000

141590.0

141589

7

10000000

1415900.0

1415899

8

100000000

14159000.0

14158999

9

1000000000

….

The final value of count as returned by this function is 17.

How to modify this code in order to achieve our desired result?

Asked By: Saaqib Mahmood

||

Answers:

Here’s a shortcut that you might like:

def num_after_point(x):
    s = str(x)
    if not '.' in s:
        return 0
    return len(s) - s.index('.') - 1
Answered By: DevShark

This was interesting! So if you run the following:

x = 3.14159  
residue = x - int(x)  
print residue  

You will get the following result:

0.14158999999999988

This decimal does in fact have 17 digits. The only way that I found to override this was to avoid doing the subtraction (which is the root cause of the error, as you can see from the inaccuracy here). So this code should work as you expect:

def number_of_digits_post_decimal(x):  
    count = 0  
    residue = x -int(x)  
    if residue != 0:  
        multiplier = 1  
        while not (x*multiplier).is_integer():  
            count += 1  
            multiplier = 10 * multiplier  
        return count

This will just shift the decimal to the right until python identifies it as an integer (it will do a rightward shift exactly the number of times you want too). Your code actually worked as you intended for it to, something unintended just happened during the subtraction process. Hope this helps!

Answered By: JPope2014
def decimal_places(f):
    exp = -1
    remainder = True
    while remainder:
        exp += 1
        a = f * 10**exp
        remainder = int(a) - a
    return(exp)
Answered By: David Martin
def precision(f):
    integer, remainder = str(f).split('.')
    return len(remainder)
Answered By: user3335499
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.