I am writing a function to extract decimals from a number. Ignore the exception and its syntax, I am working on 2.5.2 (default Leopard version). My function does not yet handle 0's. My issue is, the function produces random errors with certain numbers, and I don't understand the reason. I will post an error readout after the code.
Function:
def extractDecimals(num):
try:
if(num > int(num)):
decimals = num - int(num)
while(decimals > int(decimals)):
print 'decimal: ' + str(decimals)
print 'int: ' + str(int(decimals))
decimals *= 10
decimals = int(decimals)
return decimals
else:
raise DecimalError(num)
except DecimalError, e:
e.printErrorMessage()
Exception Class:
class DecimalError(Exception):
def __init__(self, value):
self.value = value
def printErrorMessage(self):
print 'The number, ' + str(self.value) + ', is not a decimal.'
Here is error output when I input the number 1.988:
decimal: 0.988
int: 0
decimal: 9.88
int: 9
decimal: 98.8
int: 98
decimal: 988.0
int: 987
decimal: 9880.0
int: 9879
decimal: 98800.0
int: 98799
decimal: 988000.0
int: 987999
decimal: 9880000.0
int: 9879999
decimal: 98800000.0
int: 98799999
decimal: 988000000.0
int: 987999999
decimal: 9880000000.0
int: 9879999999
decimal: 98800000000.0
int: 98799999999
decimal: 988000000000.0
int: 987999999999
decimal: 9.88e+12
int: 9879999999999
decimal: 9.88e+13
int: 98799999999999
decimal: 9.88e+14
int: 987999999999999
9879999999999998
I do not know why this error is popping up. Hopefully you guys can help me out.