0

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?

Ilya
  • 466
  • 2
  • 14
  • 1
    The accepted answer on https://stackoverflow.com/questions/2440692/formatting-floats-without-trailing-zeros seems to satisfy your needs – Adid May 17 '23 at 04:26
  • 1
    @Adid See the third thing they tried. – Nick ODell May 17 '23 at 04:27
  • @Ilya The last method that you tried returns the output that you want, isn’t it? – Dinux May 17 '23 at 04:38
  • 1
    @Dinux the questioner is aware that the last method produces the desired output, but they want to know if this is possible using [format strings](https://docs.python.org/3/reference/lexical_analysis.html#f-strings) instead of using `round()`. – import random May 17 '23 at 04:40
  • @NickODell I said the accepted answer, not the top one (which is the same as the one currently posted here). – Adid May 17 '23 at 05:01
  • 1
    I don't think there is a better way than `str(round(n,2))`, and I don't see why you consider it "risky". – blhsing May 17 '23 at 05:04

0 Answers0