#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 导入模块
from functools import reduce
def str2float(s):
def f_int(x,y): #for the integer part
return 10 * x + y
def f_dec(x,y): #for the decimal part
return 0.1 * x + y
i = s.find('.')
if (i == -1) :
num = reduce(f_int, map(int, s))
else :
intStr = list(s[0:i])
decStr = list(s[-1:i:-1])#逆序获取小数部分字符串
num = reduce(f_int, map(int, intStr)) + reduce(f_dec, map(int, decStr))/10
return num
print('str2float(\'123.456\') =', str2float('123.456'))
print('str2float(\'123456\') =', str2float('123456'))
print('str2float(\'0.123456\') =', str2float('0.123456'))
if abs(str2float('0.123456') - 0.123456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')
字符串转换为浮点数
最新推荐文章于 2024-07-19 02:10:51 发布