Discuss / Python / 字符串转浮点数

字符串转浮点数

Topic source

凡响skyline

#1 Created at ... [Delete] [Delete and Lock User]
def str2float(s: str):
    """
    去掉小数点,拼接成新的字符串
    将新字符串转为大整数,再将该整数除以10**len(point_right)
    len(point_right)是指原字符串小数点右边的位数
    """    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}    point_left, point_right = s.split('.')    new_str = point_left + point_right
    def char2num(char):        return DIGITS[char]    return reduce(lambda x, y: x * 10 + y, map(char2num, new_str)) / 10**len(point_right)

  • 1

Reply