Possible Duplicate:
Why doesn’t this division work in python?
I have this and works fine
def roi(stake, profit):
your_roi = profit / stake * 100
return your_roi
def final_roi():
roi1 = roi(52, 7.5)
print "%.2f" % roi1
final_roi()
but if I change the profit number to an int (meaning both stake and profit will have an int value) e.g. 52, 7 it is giving the output of 0.00. what's wrong there? I thought it had been formatted to be a float with the precision of two.
In python2.x,
/
does integer division (the result is an integer, truncated downward) if both arguments are of type integer. The "easy" fix is to put:at the very top of your script, or to construct a float out of one of the arguments before dividing:
Python also has an integer division operator (
//
), so you can still perform integer division if desired -- even if youfrom __future__ import division
If profit is
integer
, the division will be integer division instead of double division and you will have the result rounded down to the nearest integer number. Even if you format the number to float wehn printing it will still be 0 as it is rounded down on the assignment above.