For exactness, use the decimal class. My take on the program using decimal. Note that decimal.Decimal is imported as "dec" to avoid confusion with the variable names. Also, I am not a decimal class expert and so use divmod to get the integer and remainder/decimal portions of a number. There are probably other ways, some of which may be better. Finally, using the decimal class is much slower than floats but is not noticeable for the normal type operations.
from decimal import Decimal as dec
def extractDecimals(num):
""" the variable 'num' is expected to be a decimal.Decimal
"""
try:
whole, remainder = divmod(num, 1)
print "whole =", whole, " remainder =", remainder
if remainder > 0:
decimals = num - whole
ctr = 0
while (decimals > whole) and (ctr < 100):
ctr += 1
decimals *= 10
whole, remainder = divmod(decimals, 1)
print 'decimal: ' + str(decimals),
print ' int: ' + str(whole)
return int(decimals)
else:
raise DecimalError(num)
except DecimalError, e:
e.printErrorMessage()
extractDecimals(dec("0.988"))
Last edited by woooee; Sep 15th, 2009 at 5:03 pm.
Reputation Points: 741
Solved Threads: 691
Nearly a Posting Maven
Offline 2,302 posts
since Dec 2006