0

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.

Community
  • 1
  • 1
nutship
  • 4,624
  • 13
  • 47
  • 64

2 Answers2

1

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:

from __future__ import division

at the very top of your script, or to construct a float out of one of the arguments before dividing:

your_roi = float(profit) / stake * 100

Python also has an integer division operator (//), so you can still perform integer division if desired -- even if you from __future__ import division

mgilson
  • 300,191
  • 65
  • 633
  • 696
0

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.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176