I have some floating-point numbers containing zero or more decimal places. I want to display them with no more than two decimal places, with no trailing zeros. In other words, I'm looking for a definition of magic_fmt
that satisfies this condition:
>>> 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']
I tried a few things.
>>> [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']
The only solution that seems to work is abandoning the string formatting mini-language, which seems risky. Is there a better way?