pythonpython-3.xf-stringzero-padding

In Python 3.6+ what is the f-string to print float 9.9 as string 09.90 and 10 as 10.00?


Having looked at three other formatting questions here with tens of answers each, I don't see anyone telling how to print a float 9.9 as 09.90 and 10 as 10.00 using the same f-string:

x = 9.9
print(f"{x:02.2f}")  # Should print 09.90

x = 10
print(f"{x:02.2f}")  # Should print 10.00

The question is what should replace :02.2f above?


Solution

  • You are looking for

    print(f"{x:05.2f}")
    

    The number before the radix point is the total number of characters in the field, not the number to appear before the radix point.

    Documentation