.format won't display my value with 2 decimal places: Why?
MRAB
python at mrabarnett.plus.com
Sun Jan 24 16:20:03 EST 2016
On 2016-01-22 04:57:03, "Michael Sullivan" <msulli1355 at gmail.com> wrote:
>Hi. I'm very very new to python. I have been working my way through a
>free python pdf file I found (python3handson.pdf) and I'm having
>trouble with one of my programs:
>
>
>'''discount.py
>
>Exercise 1.14.3.1. * Write a program, discount.py, that prompts the
>user for an original price and
>for a discount percentage and prints out the new price to the nearest
>cent. For example if the user enters
>2.89 for the price and 20 for the discount percentage, the value would
>be (1- 20/100)*2.89, rounded to two
>decimal places, 2.31. For price .65 with a 25 percent discount, the
>value would be (1- 25/100)*.65, rounded
>to two decimal places, .49. 10 Write the general calculation code
>following the pattern of the calculations
>illustrated in the two concrete examples.
>
>'''
>
>oPrice = 0
>newPrice = 0
>discount = 0
>
>oPrice = input('What is the original price? ')
>discount = input('How much is this item discounted? ')
>
>oPrice = float(oPrice)
>discount = float(discount)
>newPrice = oPrice - (oPrice * discount)
>
>print('The new price is {}' .format(newPrice, '.2f'))
>
>
>When I run this thing, and I enter 5.00 for original price and .2 for
>the discount, it always results in 4.0. When I entered my format
>function call directly into the shell, it comes out like I would
>expect:
>
>
>
> >>> format(4.0, '.2f')
>'4.00'
>
>
>What exactly am I doing wrong here?
>
You're confusing the builtin 'format' function with the 'format' method
of the 'str' class.
The format function accepts a value and a format:
>>> format(4.0, '.2f')
'4.00'
The format method, on the other hand, belongs to the format string it's
attached to. In this example:
'The new price is {}' .format(newPrice, '.2f')
the format string is 'The new price is {}' and you're calling its
'format' method with 2 values for that string, the first being 4.0
(used) and the second on being '.2f' (unused).
What you want is:
print('The new price is {:.2f}'.format(newPrice))
More information about the Python-list
mailing list