44

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.

mskfisher
  • 3,291
  • 4
  • 35
  • 48
hoju
  • 28,392
  • 37
  • 134
  • 178

4 Answers4

55

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

Jonathan Graehl
  • 9,182
  • 36
  • 40
  • 3
    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) – PaulMcG Sep 15 '09 at 03:52
  • 1
    Here's what @PaulMcGuire meant, but using a `format`: `value = -3.3; print "{t:0{format}.2f}".format(format=6+(value<0), t=value)`. – Adobe Oct 04 '13 at 08:19
28

Alternatively, if you want to use .format:

              {:6.1f}
                ↑ ↑ 
                | |
# digits to pad | | # of decimal places to display

Copy paste: {:6.1f}

The 6 above includes digits to the left of the decimal, the decimal marker, and the digits to the right of the decimal.

Examples of usage:

'{:6.2f}'.format(4.3)
Out[1]: '  4.30'

f'{4.3:06.2f}'
Out[2]: '004.30'

'{:06.2f}'.format(4.3)
Out[3]: '004.30'
Josh Karpel
  • 2,110
  • 2
  • 10
  • 21
noɥʇʎԀʎzɐɹƆ
  • 9,967
  • 2
  • 50
  • 67
  • 6
    Note that this is TOTAL digits to pad including those to the right of the decimal. It isn't just digits to the left of the decimal. Took me way too long to figure out why this wasn't working – endolith Dec 20 '20 at 19:35
10

You could use str.zfill as well:

str(3.3).zfill(5)
'003.3'
Asclepius
  • 57,944
  • 17
  • 167
  • 143
Mark
  • 106,305
  • 20
  • 172
  • 230
3

A short example:

var3= 123.45678
print(
    f'rounded1    \t {var3:.1f} \n' 
    f'rounded2    \t {var3:.2f} \n' 
    f'zero_pad1   \t {var3:06.1f} \n'  #<-- important line
    f'zero_pad2   \t {var3:07.1f}\n'   #<-- important line
    f'scientific1 \t {var3:.1e}\n'
    f'scientific2 \t {var3:.2e}\n'
)

Gives the output

rounded1         123.5 
rounded2         123.46 
zero_pad1        0123.5 
zero_pad2        00123.5
scientific1      1.2e+02
scientific2      1.23e+02
Kolibril
  • 1,096
  • 15
  • 19