Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 348
jbasko Avatar asked Oct 20 '25 04:10

jbasko


2 Answers

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

like image 92
Ray Toal Avatar answered Oct 24 '25 14:10

Ray Toal


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)

like image 20
Alec Avatar answered Oct 24 '25 14:10

Alec