-2

I have some code that takes values from a dictionary and attempts to figure out the per unit price of an item. However, I cannot figure out how to keep the values from rounding.

If I do this:

total_price = int(item['Item Price'][1:]) #First character is a dollar sign
qty = int(item['Quantity'])
unit_price = total_price/qty

I get this error:

ValueError: invalid literal for int() with base 10: '88.75'

So, I tried floating the value:

total_price = int(float(item['Item Price'][1:]))
qty = int(item['Quantity'])
unit_price = total_price/qty

Which doesn't return an error, but it then rounds up and I only get whole numbers.

How can I get the actual per piece price and not a rounded value? Thanks

Wouter J
  • 41,455
  • 15
  • 107
  • 112
Dryden Long
  • 10,072
  • 2
  • 35
  • 47

2 Answers2

0

Change your qty and total_price to be a float:

total_price = float(item['Item Price'][1:])
qty = float(item['Quantity'])

This will cause the division to be between two floating point values.

Using int explicitly says you want integers, which gives you whole numbers.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

The error is occurring during division

>>> print 3/2
1
>>> print 3.0/2
1.5
>>>  
Kartik
  • 9,463
  • 9
  • 48
  • 52