Pad python floats

hoju picture hoju · Sep 15, 2009 · Viewed 29k times · Source

I want to pad some percentage values so that there are always 3 units before the decimal place. With ints I could use '%03d' - is there an equivalent for floats?

'%.3f' works for after the decimal place but '%03f' does nothing.

Answer

Jonathan Graehl picture Jonathan Graehl · Sep 15, 2009

'%03.1f' works (1 could be any number, or empty string):

>>> "%06.2f"%3.3
'003.30'

>>> "%04.f"%3.2
'0003'

Note that the field width includes the decimal and fractional digits.