Search code examples
pythonpython-3.xstring-formatting

Fixed-point notation is not behaving acording to the documentation


I want to format some values with a fixed precision of 3 unless it's an integer. In that case I don't want any decimal point or trailing 0s.

Acording to the docs, the 'f' type in string formating should remove the decimal point if no digits follow it:

If no digits follow the decimal point, the decimal point is also removed unless the # option is used.

But testing it with python3.8 I get the following results:

>>> f'{123:.3f}'
'123.000'
>>> f'{123.0:.3f}'
'123.000'

Am I misunderstanding something? How could I achive the desired result without using if else checks?


Solution

  • In order to forcefully achieve both your desired outputs with the same f-string expression, you could apply some kung-fu like

    i = 123
    f"{i:.{3*isinstance(i, float)}f}"
    # '123'
    
    i = 123.0
    f"{i:.{3*isinstance(i, float)}f}"
    # '123.000'
    

    But this won't improve your code in terms of readability. There's no harm in being more explicit.