从Python中的数字中提取小数

dbm*_*kus 1 python python-2.5

我正在编写一个从数字中提取小数的函数.忽略异常及其语法,我正在研究2.5.2(默认的Leopard版本).我的功能尚未处理0.我的问题是,该函数产生具有某些数字的随机错误,我不明白其中的原因.我将在代码后发布错误读数.


功能:

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()
Run Code Online (Sandbox Code Playgroud)


例外类:

class DecimalError(Exception):
    def __init__(self, value):
        self.value = value

    def printErrorMessage(self):
        print 'The number, ' + str(self.value) + ', is not a decimal.'
Run Code Online (Sandbox Code Playgroud)


输入数字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



我不知道为什么会出现这个错误.希望你们能帮助我.

Ned*_*der 5

问题是(二进制)浮点数不能精确表示为小数.请参阅为什么十进制数不能完全用二进制表示?欲获得更多信息.