注册 登录
编程论坛 Python论坛

str转换为float浮点数后,结果展示问题

似水流年去 发布于 2017-12-14 10:31, 1375 次点击
程序代码:
CHAR_TO_FLOAT = {
    '0': 0,
    '1': 1,
    '2': 2,
    '3': 3,
    '4': 4,
    '5': 5,
    '6': 6,
    '7': 7,
    '8': 8,
    '9': 9,
    '.': -1
}

def str2float1(s):
    nums = map(lambda ch: CHAR_TO_FLOAT[ch], s)
    point = 0
    def to_float(f, n):
        nonlocal point
        if n == -1:
            point = 1
            return f
        if point == 0:
            return f * 10 + n
        else:
            point = point * 10
            return f + n / point
    return reduce(to_float, nums, 0.0)

用:print(str2float1('120.123'))打印时,结果为:120.12299999999999能解释下不?
0 回复
1