Reputation: 35
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?
Upvotes: 0
Views: 2498
Reputation: 73460
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.")
Upvotes: 1