Discuss / Python / str2float函数,我也来一个

str2float函数,我也来一个

Topic source
# -*- coding: utf-8 -*-
from functools import reduce

def str2float(s):
    a=s.split('.',1)
    return reduce(lambda x,y:x*10+y,map(int,a[0]))+reduce(lambda x,y:x*10+y,map(int,a[1]))/10**len(a[1])

print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')
#print result
str2float('123.456') = 123.456
测试成功!


  • 1

Reply