将字符串尾随零的数字转换为float时,我遇到以下问题:
a = 1.100
string_a = str(a)
float_a = float(string_a)
float_a = 1.1
有没有办法将str转换为float,同时将尾随的0保持在最后?
答案 0 :(得分:9)
首先不保留零:
>>> 1.100
1.1
>>> 1.100 == 1.1
True
但是当你打印出来时,你可以使用字符串格式来保存它们:
>>> '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'