如果您拥有Python 2.6或更高版本,请使用format
:
'{0:.3g}'.format(num)
对于Python 2.5或更早版本:
'%.3g'%(num)
说明:
{0}
告诉format
打印第一个参数-在这种情况下为num
。
冒号(:)之后的所有内容均指定format_spec
。
.3
将精度设置为3。
g
删除无关紧要的零。请参阅http://en.wikipedia.org/wiki/Printf#fprintf
例如:
tests=[(1.00, '1'),
(1.2, '1.2'),
(1.23, '1.23'),
(1.234, '1.23'),
(1.2345, '1.23')]
for num, answer in tests:
result = '{0:.3g}'.format(num)
if result != answer:
print('Error: {0} --> {1} != {2}'.format(num, result, answer))
exit()
else:
print('{0} --> {1}'.format(num,result))
产量
1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23
使用Python 3.6或更高版本,您可以使用f-strings
:
In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'