Search code examples
pythondivisiondivide

Not sure how to retain the decimal when dividing numbers


Sorry in advance, I'm pretty new to coding so if this is a common question I apologize, though I couldn't find an answer to the issue I was having.

I have a value that is losing it's decimal so the program is not calculating the amount needed in the way I'm intending. The original input is 2.5, so the .5 is falling off and in turn outputting a value that is only 80% of what the full output should be.

It's my understanding that you should be able to divide two float values, but I can't get it to work which is why I've been converting my float values, to int and then back to float for the outputs but it doesn't feel right.

Here are some statements where the variable is being used. If necessary I can provide the full code. Basically, on the third line down, I'm dividing by the number of servings so that I can then multiply the proper amount based on the number of servings being input. This results in a decimal value where the decimal value is being lost when I convert the variable to int.

agave_nectar = format(agave_nectar, ".2f")
print(agave_nectar, "cup(s) agave nectar\n")
agave_nectar = agave_nectar / servings
agave_nectar = agave_nectar * servings
agave_nectar = format(agave_nectar, ".2f")
print(agave_nectar, "cup(s) agave nectar\n")
agave_nectar = int(float(agave_nectar))
agave_nectar /= 16
agave_nectar = format(agave_nectar, ".2f")
print(agave_nectar, "gallon(s) agave nectar")

The problem I run into when trying to divide two float values is this:

Traceback (most recent call last):
  File "main.py", line 16, in <module>
    lemon_juice_cups = lemon_juice_cups / servings
TypeError: unsupported operand type(s) for /: 'str' and 'str'

Solution

  • You think you are dividing using two float values, but you are actually operating using two strings. That is evident from the TypeError you are getting on line 16.

    Please try the following instead:

    lemon_juice_cups = float(lemon_juice_cups) / float(servings)