Jerry Cui
Jerry Cui

Reputation: 149

How do you let a user input a decimal number?

I am trying to make a program related to money and the user needs to input a decimal. But it always gives me an error. Here is the code:

price = input("What is the price of your vegetable?")
pounds = input("How many pounds did you buy?")

price = int(price)
pounds = int(pounds)

if pounds < 5:
    price = price * 1
    print("Your price is " + str(price))
elif pounds < 10:
    price = price * 0.90
    print("Your price is " + str(price))
elif pounds < 20:
    price = price * 0.80
    print("Your price is " + str(price))
elif pounds > 30:
    price = price * 0.75
    print("Your price is " + str(price))

And here is the error:

What is the price of your vegetable?6.72
How many pounds did you buy?4
Traceback (most recent call last):
File "C:/Users/Jerry Cui/Documents/pricediscount.py", line 4, in <module>
    price = int(price)
ValueError: invalid literal for int() with base 10: '6.72'

Where is the problem?

Upvotes: 0

Views: 3355

Answers (3)

itprorh66
itprorh66

Reputation: 3288

If your dealing with financial data it is best to employ the decimal module. The according to the docs see decimal — Decimal fixed point and floating point arithmetic the module provides support for fast correctly-rounded decimal floating point arithmetic. It offers several advantages over the float datatype. To use in your particular situation:

price = input("What is the price of your vegetable? (pounds.pence, e.g: 3.42)")
price = Decimal(price).quantize(Decimal('.01'), rounding=ROUND_DOWN))

As examples:
print(Decimal('12.345').quantize(Decimal('.01'), rounding=ROUND_DOWN))) -> 12.34 , and

print(Decimal(''123.0056'').quantize(Decimal('.01'), rounding=ROUND_DOWN))) -> 123.00

Upvotes: 0

Joe Iddon
Joe Iddon

Reputation: 20414

Use float() as you want to allow entry of floats!

However, I suggest you read this, which hopefully will convince you to right something along the lines of:

price = input("What is the price of your vegetable? (pounds.pence, e.g: 3.42)")
price = int(price.replace(".", ""))

Now the price is stored as an integer, which is much more accurate than a float; especially when storing money (hence we use int() here again).

Upvotes: 1

Ronan Boiteau
Ronan Boiteau

Reputation: 10138

Use float() instead of int():

price = float(price)
pounds = float(pounds)

  • int() converts to an integer
  • float() converts to a decimal

Upvotes: 2

Related Questions