views:

327

answers:

2
+1  Q: 

Pad python floats

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.

+10  A: 

'%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.

wrang-wrang
If the value is negative, the leading '-' will consume one of the field width count - "%06.2f" % -3.3 gives "-03.30", so if you must have 3 digits even if negative, you'll have to add one more to the field width. You can do that using the '*' fieldwidth value, and pass a computed value: value = -3.3; print "%0*.2f" % (6+(value<0),value)
Paul McGuire
+2  A: 

You could use zfill as well,.

str(3.3).zfill(5)
'003.3'
Mark