Search code examples
pythonimportdecimalroundingcurrency

Python - How to remove decimals without rounding up


Im a little new into python, and i wanted to test it out, my idea was to make a script, that would see how much stuff you could buy for a certain amount of money. The problem with this project though, is that i dont know remove the decimals, just like you like if you had 1,99 dollar and a soda costed 2 dollar, you technically wouldn't have enough money for it. Here is my script:

Banana = 1
Apple = 2
Cookie = 5

money = input("How much money have you got? ")
if int(money) >= 1:
    print("For ", money," dollars you can get ",int(money)/int(Banana),"bananas")
if int(money) >= 2:
    print("Or ", int(money)/int(Apple), "apples")
if int(money) >= 5:
    print("Or ", int(money)/int(Cookie)," cookies")
else:
    print("You don't have enough money for any other imported elements in the script")

Now, if i enter for example, 9 in this script, it will say i can get 1.8 cookies, how do i make it say i can get 1 cookies when entering fx 9?


Solution

  • I suspect you are using Python 3, because you are talking about getting the float result 1.8 when you are dividing two integers 9 and 5.

    So in Python 3, there is an integer division operator // you can use:

    >>> 9 // 5
    1
    

    vs

    >>> 9 / 5
    1.8
    

    As for Python 2, the / operator by default does the integer division (when both operands are ints), unless you use from __future__ import division to make it behave like Python 3.