Discuss / Python / 字符串转换成浮点数

字符串转换成浮点数

Topic source

xiaofeig002

#1 Created at ... [Delete] [Delete and Lock User]
#将字符串转换成浮点数
def str2float(s):
    def char2num(c):
        return {"0":0, "1":1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9}[c]
    l=s.split(".")
    num1=reduce(lambda x, y: x*10+y, map(char2num, l[0]))
    num2=reduce(lambda x, y: x*10+y, map(char2num, l[1]))
    return num1+num2*pow(10, -len(l[1]))
print(str2float("234.234"))

  • 1

Reply