Search code examples
pythonstring-formatting

Python formatting integer (fixed digits before/after the decimal point)


I was wondering if it's possible to use two format options together when formatting integers.

I know I can use the bellow to include zero places

varInt = 12

print(
    "Integer : " +
    "{:03d}".format(varInt)
)

To get the output "Integer : 012"

I can use the following to include decimal places

varInt = 12

print(
    "Integer : " +
    "{:.3f}".format(varInt)
)

To get the output "Integer : 12.000"

But is it possible to use them both together to get the output "Integer : 012.000"


Solution

  • varInt = 12
    
    print(
        "Integer : " +
        "{:07.3f}".format(varInt)
    )
    

    Outputs:

    Integer : 012.000
    

    The 7 is total field width and includes the decimal point.