TheLovelySausage
TheLovelySausage

Reputation: 4094

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"

Upvotes: 15

Views: 70968

Answers (4)

Shinsuke Hamasho
Shinsuke Hamasho

Reputation: 61

For anyone who came here to format numbers in f string:

>>> a = 12
>>> f"{a:07.3f}"
'012.000'

Upvotes: 3

GP89
GP89

Reputation: 6730

Sure, the number at the beginning is the minimum length of the outputted string, so include the decimal part and the decimal point as well.

>>> "{:07.3f}".format(12)
'012.000'

Upvotes: 6

John La Rooy
John La Rooy

Reputation: 304137

Not only can you specify the minimum length and decimal points like this:

"{:07.3f}".format(12)

You can even supply them as parameters like this:

"{:0{}.{}f}".format(12, 7, 3)

Upvotes: 5

Andy
Andy

Reputation: 50540

varInt = 12

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

Outputs:

Integer : 012.000

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

Upvotes: 19

Related Questions