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

Modulok modulok at gmail.com
Sat Mar 5 07:25:06 CET 2011

On 3/4/11, lea-parker at bigpond.com <lea-parker at bigpond.com> wrote:
> Hello
> I have created the following code but would like the program to include two
> decimal places in the amounts displayed to the user. How can I add this?
> My code:
> # Ask user to enter purchase price
> purchasePrice = input ('Enter purchase amount and then press the enter key
> $')
> # Tax rates
> stateTaxRate = 0.04
> countrySalesTaxRate = 0.02
> # Process taxes for purchase price
> stateSalesTax = purchasePrice * stateTaxRate
> countrySalesTax = purchasePrice * countrySalesTaxRate
> # Process total of taxes
> totalSalesTax = stateSalesTax + countrySalesTax
> # Process total sale price
> totalSalePrice = totalSalesTax + purchasePrice
> # Display the data
> print '%-18s %9d' % ('Purchase Price',purchasePrice)
> print '%-18s %9d' % ('State Sales Tax',astateSalesTax)
> print '%-18s %9d' % ('Country Sales Tax',countrySalesTax)
> print '%-18s %9d' % ('Total Sales tax',totalSalesTax)
> print '%-18s %9d' % ('Total Sale Price',totalSalePrice)


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.
(See: http://docs.python.org/library/stdtypes.html#str.format)

Here's an example you could put at the bottom of your code to see it in action:

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


More information about the Tutor mailing list