Wanted to ask, why
5 / 100
returns
0
, but it works with
5 * 0.01
, even though arithmetically both should return the same value?
even float(5 / 100)
returns 0.0
Wanted to ask, why
5 / 100
returns
0
, but it works with
5 * 0.01
, even though arithmetically both should return the same value?
even float(5 / 100)
returns 0.0
I'm guessing you are using Python 2.x, because 5 / 100
returns 0.05
on Python 3.x
To achieve the behavior you want on Python 2.x, you need to inherit this functionality:
from __future__ import division
print 5 / 100 # Yields 0.05
If you only want to do this just one time and not modify the interpreter default behavior, you can just cast one of the operands to float
print 5 / float(100) # Yields 0.05
5/100
return 0
because you are dividing two integers, not floating point numbers. Division of any two integers will return an integer number.
Same reason for float(5/100)
. In this case you are first dividing two integers and then converting its result, which is integer 0
, to floating point number.
If any of the number in the arithmetic operation is a floating point number, then the result would be also be a floating point number.
For example, float(5)/100
. This will return 0.05
because you are dividing a floating point number, i.e. float(5)
, by an integer 100
.