0

How do I allow someone to enter a float integer with a "$" in front of the value. For example, they could enter "$4.25" and also they could enter "4.25".

Also, when I enter "4.35" into my calculator the tip comes out as "0.6". On a calculator I own at home it comes out as 0.6525. How do I get the whole answer?

input ('Please Enter to begin')

while True:
    print('This calculator will display the tip you owe for your meal price.')
    mealPrice = int(float(input('Enter your meal price:')))
    asw = mealPrice * 0.15
    print('The tip you owe is: $',asw)

    endProgram = input ('Do you want to restart the program?')

    if endProgram in ('no', 'No', 'NO', 'false', 'False', 'FALSE'):
        break
JordanDevelop
  • 143
  • 1
  • 6
  • 21
  • Is this Python 3 or 2.X? – David Robinson Jan 30 '13 at 20:11
  • 2
    Incidentally, why are you casting the `float` to an `int`? That truncates the price to the nearest dollar, which isn't necessary (if you left it as a float it would calculate it as an exact tip) – David Robinson Jan 30 '13 at 20:14
  • To expand on @DavidRobinson's point about `int` not being desirable, you can to limit the output to two decimal places using string formatting: `print("The tip you owe is: ${:.2f}".format(asw))` – Blckknght Jan 30 '13 at 20:18
  • 1
    Did you just ask this earlier? http://stackoverflow.com/questions/14611344/python-im-making-a-simple-calculator-for-class-whats-wrong-with-this-code/14612909#14612909 – Cassandra S. Jan 30 '13 at 20:22

1 Answers1

5

Change

mealPrice = int(float(input('Enter your meal price:')))

to

mealPrice = float(input('Enter your meal price:').lstrip("$"))

lstrip("$") removes any occurrences of the given character from the left side of the string. You also need to remove the int, which truncates the price to the nearest dollar (and is the reason you're getting the wrong answer sometimes).

David Robinson
  • 77,383
  • 16
  • 167
  • 187
  • aren't you supposed to use "input instead of "raw_input" in Python 3.3.0? Anyway, this worked. Thank you. – JordanDevelop Jan 30 '13 at 20:16
  • @Blckknght: I wasn't sure about Python 3 (while it's true that the OP wouldn't need `float(` in Python 3, the OP also doesn't need `int`, so I figured it's possible both calls are unnecessary). However, given that the print statements are used as a function that takes two arguments I do agree that it's probably Python 3. – David Robinson Jan 30 '13 at 20:17
  • @JordanSimps: That's the reason I asked `Is this Python 3 or 2.X?` in a comment – David Robinson Jan 30 '13 at 20:18
  • @DavidRobinson you need either float() or int(), since input returns strings. – Cassandra S. Jan 30 '13 at 20:23
  • 1
    @RobertS.: Typo- comment should have been `wouldn't need float in Python 2` – David Robinson Jan 30 '13 at 20:34