Discuss / Python / 321
dic_char_to_num = {    '1': 1,    '2': 2,    '3': 3,    '4': 4,    '5': 5,    '6': 6,    '7': 7,    '8': 8,    '9': 9,    '0': 0}

def char_to_num(c: str):
    return dic_char_to_num[c] if c in dic_char_to_num.keys() else ''

def str2float(s: str):
    number = reduce(lambda x, y: x * 10 + y, [n for n in map(char_to_num, s) if isinstance(n, int)])
    if '.' in s:
        o = iter(range(len(s)-s.index('.')-1))
        while True:
            try:
                next(o)
                number *= 0.1
            except StopIteration:
                break
    return number

此处有一个很好的 浮点数精度问题的现象表现

另外,用   

number *= 0.1

number /= 10

会得到两个不同的结果值


  • 1

Reply