0

In some simple mathematics, here I am trying to get the percentage of targets which have been done from the total number. The ones which have been done are positive. In my understanding, the following mathematics should give me a percentage of 50, but running it, Python insists on giving me zero. Why would that be?

Total =  2
Positives = 1
Percentage = (Positives/Total)*100
print ('Percentage is: ' + str(Stat) + '%\n' )

>>>Percentage is: 0%
user3070849
  • 41
  • 2
  • 6

3 Answers3

2

In Python 2, the division operator (/) returns an int if both arguments are integers, and a float if at least one of the arguments is a float.

print 1 / 2   # 0
print 1 / 2.0 # 0.5

You can force floating-point division with the from __future__ import division directive.

from __future__ import division
print 1 / 2  # 0.5
print 1 // 2 # 0 (// is always integer division)

Python 3 has floating-point division enabled by default.

Also, note that the // operator, integer division, exists in both Python 2 and 3, even if you don't have from __future__ import division, and will always return an integer.

Finally, note that we're talking about floating-point numbers (http://en.wikipedia.org/wiki/IEEE_floating_point_number), not decimals here. If you really want decimals (slower, but with arbitrary precision), take a look at the decimal module in the Python standard library.

Max Noel
  • 8,810
  • 1
  • 27
  • 35
1

To literally declare a float add a .0 at the end of it:

>>>Total =  2.0
>>>Positives = 1.0
>>>Percentage = (Positives/Total)*100
>>>print Percentage
50.0

In Python2 division between two integers returns an integer. You'll need at least a float in the division to make it return a float.

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
1

If you put all integers into an equation, Python assumes that you want an integer as a result.
(int / int == int) So the following code returns a zero:

>>> 1/2
0 

If you want a float in the result, you need to make sure that one of your input variables is a float:
(int / float = float) or (float / int = float)

>>> 1/2.0
0.5

You can also use a cast to do the same thing:

>>> float(1)/2
0.5

Not that you must change one of the variables to a float BEFORE the division happens, or you will get an unexpected result. The following commands divides int(1)/int(2), which returns 0, then trying to cast the 0 to a float:

>>> float(1/2)
0.0
Kevin
  • 2,112
  • 14
  • 15