How can I force division to be floating point? Division keeps rounding down to 0
I have two integer values a
and b
, but I need their ratio in floating point. I know that a<b
and I want to calculate a/b
, so if I use integer division I'll always get 0 with a remainder of a
.
How can I force c
to be a floating point number in Python in the following?
c = a / b
>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663
You can cast to float by doing c = a / float(b)
. If the numerator or denominator is a float, then the result will be also.
A caveat: as commenters have pointed out, this won't work if b
might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.
c = a / (b * 1.0)
链接地址: http://www.djcxy.com/p/8508.html
上一篇: JSON2与jQuery的比较