float is OK, int gives wrong output python 2.7 [du

2020-05-03 07:27发布

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.

2条回答
▲ chillily
2楼-- · 2020-05-03 08:07

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

查看更多
放荡不羁爱自由
3楼-- · 2020-05-03 08:10

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.

查看更多
登录 后发表回答