WHat是像这样格式化python十进制的好方法吗?
1.00 - > '1'
1.20 - > '1.2'
1.23 - > '1.23'
1.234 - > '1.23'
1.2345 - > '1.23'
Answers:
如果您拥有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'
Exponent notation
。作为{:,2f}.format(number)
剂量,但也删除了不重要的零点
贾斯汀的答案只有第一部分是正确的。使用“%.3g”不适用于所有情况,因为.3不是精度,而是总位数。尝试使用1000.123之类的数字,它会中断。
因此,我会使用贾斯汀的建议:
>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'
这是一个可以解决问题的函数:
def myformat(x):
return ('%.2f' % x).rstrip('0').rstrip('.')
这是您的示例:
>>> myformat(1.00)
'1'
>>> myformat(1.20)
'1.2'
>>> myformat(1.23)
'1.23'
>>> myformat(1.234)
'1.23'
>>> myformat(1.2345)
'1.23'
编辑:
通过查看其他人的答案和实验,我发现g为您完成了所有剥离工作。所以,
'%.3g' % x
的功能也非常出色,并且与其他人的建议略有不同(使用'{0:.3}'。format()东西)。我猜你选。
只需使用Python的标准字符串格式设置方法即可:
>>> "{0:.2}".format(1.234232)
'1.2'
>>> "{0:.3}".format(1.234232)
'1.23'
如果您使用的是2.6以下的Python版本,请使用
>>> "%f" % 1.32423
'1.324230'
>>> "%.2f" % 1.32423
'1.32'
>>> "%d" % 1.32423
'1'
{:g}
不会从小数点中删去无关紧要的零。