0

I need to count the number of decimal places in a user-inputted float so that my code will not accept any number with more or less than 2 decimal places (the number is supposed to be a price). Here is my code:

        while(flag == True):

        try:
            price = input("Enter the price: ")
            price = float(price)
            flag = False

            #price must be positive
            if float(price) < 0:
                print("Invalid input for the new price.")
                flag = True

        #check for 2 decimal places
        decimal = str(price)
        decimal = decimal.split(".")
        if len(decimal[1]) != 2:
            print("Invalid input for the new price.")
            flag = True 

As of now it is working, except if I enter a price like 6.50, where the last decimal place is a 0. For some reason it is not accepting any number that ends in 0 as 2 decimal places. How can I fix this?

gumbo1234
  • 35
  • 5
  • 1
    What is the `type` of price? Why are you not checking the user input directly which should be a string already? – user2390182 Dec 03 '17 at 16:45
  • @schwobaseggl see updated code – gumbo1234 Dec 03 '17 at 16:49
  • 1
    You shouldn't be converting the price to a `float` at all! Floating point is for measurements on a continuous scale, but money is always measured in discrete units and thus you should avoid `float` and use [`decimal`](https://docs.python.org/3.6/library/decimal.html) directly. – Daniel Pryden Dec 03 '17 at 17:10
  • Possible duplicate of [How to round a Python Decimal to 2 decimal places?](https://stackoverflow.com/questions/23583273/how-to-round-a-python-decimal-to-2-decimal-places) – Daniel Pryden Dec 03 '17 at 17:13

1 Answers1

1

Just reverse the checking and float conversion order and you won't have the problem that the float conversion implicitly strips the '0':

str(float('6.50'))
# '6.5'

Do sth like:

# price = input("Enter the price: ")
price = raw_input("Enter the price: ")  # python2
try:
    assert len(price.split(".")[1]) == 2
    price = float(price)
except (AssertionError, ValueError):
    print("Invalid input for the new price.")
user2390182
  • 72,016
  • 6
  • 67
  • 89