Skip to content Skip to sidebar Skip to footer

Find The Number Of Digits After The Decimal Point

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 c

Solution 1:

Here's a shortcut that you might like:

defnum_after_point(x):
    s = str(x)
    ifnot'.'in s:
        return0returnlen(s) - s.index('.') - 1

Solution 2:

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 = 1whilenot (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!

Post a Comment for "Find The Number Of Digits After The Decimal Point"