2

I am trying to use .format() to format my output. I am trying to align the float to be centered, occupy a width of 12 and only display 2 decimal points.

I already have it working to be centered and occupy a width of 12 as follows:

print "{:^12}".format(dig)

However, how do I add the two decimal places format into this? I know it's .2f, but how do I combine it all? I tried adding it after the 12, before the : and at all sorts of places - it would always throw back an error.

Thanks!

1

2 Answers 2

9

Just use 12.2f:

>>> print "|{:^12.2f}|".format(145.6798)
|   145.68   |

used | just to prove that the 12 width is working.

1

Here's the documentation for the format specification:

dig = 22/7.0   # 3.142857142857143

print "->123456789012<-"
print "->{:^12.2f}<-".format(dig)   # using .2f as you expected
              ^^^

will give you

->123456789012<-
->    3.14    <-  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.