Python 字符串格式以确保精确且没有尾随零

问题描述 投票:0回答:0

我有一些包含零个或多个小数位的浮点数。我想用不超过两位小数来显示它们,没有尾随零。换句话说,我正在寻找满足此条件的

magic_fmt
的定义:

>>> ls = [123, 12, 1, 1.2, 1.23, 1.234, 1.2345]
>>> [magic_fmt(n, 2) for n in ls]
['123', '12', '1', '1.2', '1.23', '1.23', '1.23']

我尝试了一些东西。

>>> [f'{n:.2e}' for n in ls] # not right at all
['1.23e+02',
 '1.20e+01',
 '1.00e+00',
 '1.20e+00',
 '1.23e+00',
 '1.23e+00',
 '1.23e+00']
>>> [f'{n:.2f}' for n in ls] # has trailing zeros
['123.00', '12.00', '1.00', '1.20', '1.23', '1.23', '1.23']
>>> [f'{n:.2g}' for n in ls] # switches to exponential notation when I don't want it to
['1.2e+02', '12', '1', '1.2', '1.2', '1.2', '1.2']
>>> [str(round(n,2)) for n in ls]
['123', '12', '1', '1.2', '1.23', '1.23', '1.23']

似乎唯一可行的解决方案是放弃字符串格式化迷你语言,这似乎有风险。有更好的方法吗?

python string-formatting
© www.soinside.com 2019 - 2024. All rights reserved.