Search code examples
pythonfloating-pointzeropad

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.


Solution

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