从str转换为float时保持尾随0 [英] Keeping trailing 0 when converting from str to float

查看:61
本文介绍了从str转换为float时保持尾随0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将带有尾随零的数字从字符串转换为浮点数时,我遇到以下问题:

I have the following problem when converting a number with trailing zeros from string to float:

a = 1.100
string_a = str(a)
float_a = float(string_a)
float_a = 1.1

有没有一种方法可以将str转换为浮点数,同时将结尾的0保留在末尾?

Is there a way to convert str to float while keeping the trailing 0s at the end?

推荐答案

零不放在首位:

>>> 1.100
1.1
>>> 1.100 == 1.1
True

但是您可以在打印出来时使用字符串格式来保留它们:

But you can use string formatting to preserve them when you print it out:

>>> 'It works: {:0.3f}'.format(1.1)
'It works: 1.100'
>>> 'And even with integers: {:0.3f}'.format(10000)
'And even with integers: 10000.000'

这篇关于从str转换为float时保持尾随0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆