当前位置: 代码网 > it编程>前端脚本>Python > python字符串转换成浮点数的实现方式

python字符串转换成浮点数的实现方式

2026年03月23日 Python 我要评论
将字符串型数字‘123.456’转换成float型数据直接自带float就行啦 test1 ="123.456" test2 = '12.304' test3 = '12.34

将字符串型数字‘123.456’转换成float型数据

直接自带float就行啦

 test1 ="123.456"
 test2 = '12.304'
 test3 = '12.34'
 print(float(test1))
 print(float(test2))
 print(float(test3))

结果:

123.456
12.304
12.34

使用map和reduce把字符串型数字‘123.456’转换成浮点数123.456

from functools import reduce
def str2float(s):
    def fn(x,y):
            return x*10+y
    n=s.index('.')
    s1=list(map(int,[x for x in s[:n]]))
    s2=list(map(int,[x for x in s[n+1:]]))
    return reduce(fn,s1)+reduce(fn,s2)/10**len(s2)

测试:

 str = "123.456"
 str2float(str)
 123.456

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com