Consider:
>>> numerator = 29
>>> denom = 1009
>>> print str(float(numerator/denom))
0.0
How do I make it return a decimal?
The division result of two numbers can be an integer or a floating-point number. In python version 3+, both the single slash (/) operator and the double slash (//) operator are used to get the division result containing the floating-point value.
// int DivisionThe / operator always produce a float. However many algorithms make the most sense if all of the values are kept as ints, so we need a different sort of division operator that produces ints. In Python the int-division operator // rounds down any fraction, always yielding an int result.
In Python, there are two types of division operators: / : Divides the number on its left by the number on its right and returns a floating point value. // : Divides the number on its left by the number on its right, rounds down the answer, and returns a whole number.
Behavior of the division operator in Python 2.7 and Python 3 // is not "used for integer output". // is the result of the floor() function to the result of the division, which in turns yields an integer if the two operands are integers and a float if at least one of them is a float, for types coherence.
Until version 3, Python's division operator, /, behaved like C's division operator when presented with two integer arguments: it returns an integer result that's truncated down when there would be a fractional part. See: PEP 238
>>> n = 29
>>> d = 1009
>>> print str(float(n)/d)
0.0287413280476
In Python 2 (and maybe earlier) you could use:
>>> from __future__ import division
>>> n/d
0.028741328047571853
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With