[Tutor] Help - want to display a number with two decimal places

Steven D'Aprano steve at pearwood.info
Sat Mar 5 10:59:44 CET 2011

Modulok wrote:

> Notice that 'd' in your string substitution means integers, not
> floats. Any decimal places will be truncated when using 'd'. For
> floats use 'f' instead. You an also specify a precision, such as
> '%.2f' shows two decimal places.
> However, to make all of your numbers line up nicely, regardless of how
> long they are, you need to look into advanced string formatting via
> the builtin string method 'format()'. It takes a little practice to
> understand and use, but the results are exactly what you want.

str.format only exists from Python 2.6, but in any case, it certainly 
isn't true that you "need" to look at format to make numbers line up 
nicely. The examples you give can all be written using string interpolation:

> print "{0:<18} {1:>18.2f}".format("Country Sales Tax", countrySalesTax)
> print "{0:<18} {1:>18.2f}".format("Purchase Price", purchasePrice)
>     # First prints the first argument (the 0th index) to 'format(),
>     # left aligned '<', and 18 characters wide, whitespace padded.
>     # Then prints the second argument, (the 1st index) right aligned,
>     # also 18 characters wide, but the second argument is specified to
>     # be a float 'f', that has a precision of 2 decimal places, '.2'.

 >>> countrySalesTax = 11.25
 >>> purchasePrice = 124577.35
 >>> print "%-18s %18.2f" % ("Country Sales Tax", countrySalesTax); \
... print "%-18s %18.2f" % ("Purchase Price", purchasePrice)
Country Sales Tax               11.25
Purchase Price              124577.35

str.format can do some things better than % interpolation, but 
formatting strings to a width is not one of them. It's also a matter of 
opinion which is more cryptic:

"%-18s %18.2f"
"{0:<18} {1:>18.2f}"


More information about the Tutor mailing list