0

hHaving 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 be in place of :02.2f in the above?

Alec
  • 8,529
  • 8
  • 37
  • 63
jbasko
  • 7,028
  • 1
  • 38
  • 51
  • Does it matter what happens with negative numbers? Do you want `-9.90` or `-09.90`? Or will you simply never have negative numbers? – AJNeufeld May 25 '19 at 19:16
  • Thanks, it doesn't matter. This is used for a timer so once it runs out, it will be 00.00. – jbasko May 25 '19 at 19:25

2 Answers2

6

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

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
3
f'{x:.2f}'

will print x to two decimal places.

f'{x:05.2f}'

will print x to two decimal places, with five total characters (including the decimal point)

Alec
  • 8,529
  • 8
  • 37
  • 63