什么是这样格式化python十进制的好方法?
1.00 - > '1'
1.20 - > '1.2'
1.23 - > '1.23'
1.234 - > '1.23'
1.2345 - > '1.23'
unu*_*tbu 108
如果您使用的是Python 2.6或更高版本,请使用format:
'{0:.3g}'.format(num)
Run Code Online (Sandbox Code Playgroud)
对于Python 2.5或更早版本:
'%.3g'%(num)
Run Code Online (Sandbox Code Playgroud)
说明:
{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))
Run Code Online (Sandbox Code Playgroud)
产量
1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23
Run Code Online (Sandbox Code Playgroud)
使用Python 3.6或更高版本,您可以使用f-strings:
In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'
Run Code Online (Sandbox Code Playgroud)
小智 21
只有贾斯汀的第一部分答案是正确的.使用"%.3g"不适用于所有情况,因为.3不是精度,而是总位数.尝试使用像1000.123这样的数字,它会中断.
所以,我会用Justin的建议:
>>> ('%.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'
Run Code Online (Sandbox Code Playgroud)
Jus*_*eel 12
这是一个可以解决问题的功能:
def myformat(x):
return ('%.2f' % x).rstrip('0').rstrip('.')
Run Code Online (Sandbox Code Playgroud)
这是你的例子:
>>> myformat(1.00)
'1'
>>> myformat(1.20)
'1.2'
>>> myformat(1.23)
'1.23'
>>> myformat(1.234)
'1.23'
>>> myformat(1.2345)
'1.23'
Run Code Online (Sandbox Code Playgroud)
编辑:
从查看其他人的答案和实验,我发现g为你做了所有剥离的东西.所以,
'%.3g' % x
Run Code Online (Sandbox Code Playgroud)
也很出色,与其他人的建议略有不同(使用'{0:.3}'.format()东西).我想你的选择.
Wea*_*n X 11
如果使用 3.6 或更高版本,只需使用f-Strings
print(f'{my_var:.1f}')
Run Code Online (Sandbox Code Playgroud)
que*_*o42 10
您可以使用“f-strings”(f 表示“格式化字符串文字”),这是 Python 中的短格式样式v3.6:
f'{1.234:.1f}'
Out: '1.2'
Run Code Online (Sandbox Code Playgroud)
或者,作为测试:
f'{1.234:.1f}' == '1.2'
Out: True
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您也可以将其与变量一起使用。
x = 1.234
f'{x:.1f} and {x:.2f} and {x}'
Out: '1.2 and 1.23 and 1.234'
Run Code Online (Sandbox Code Playgroud)
如果需要在文本中使用引号,请将文本嵌入为f'''...'''而非f'...'。
只需使用 Python 的标准字符串格式化方法:
>>> "{0:.2}".format(1.234232)
'1.2'
>>> "{0:.3}".format(1.234232)
'1.23'
Run Code Online (Sandbox Code Playgroud)
如果您使用的 Python 版本低于 2.6,请使用
>>> "%f" % 1.32423
'1.324230'
>>> "%.2f" % 1.32423
'1.32'
>>> "%d" % 1.32423
'1'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
135742 次 |
| 最近记录: |