0

In python, i cannot divide 5 by 22. When I try this, it gives me zero-even when i use float?!!

>>> print float(5/22)
0.0
MattDMo
  • 100,794
  • 21
  • 241
  • 231
user3749089
  • 21
  • 1
  • 2
  • possible duplicate of [how can I force division to be floating point in Python?](http://stackoverflow.com/questions/1267869/how-can-i-force-division-to-be-floating-point-in-python) – senshin Jul 09 '14 at 16:00

2 Answers2

7

It's a problem with order of operations. What's happening is this: * First python takes 5/22. Since 5 and 22 are integers, it returns an integer result, rounding down. The result is 0 * Next you're converting to a float. So float(0) results in 0.0

What you want to do is force one (or both) operands to floats before dividing. e.g.

  • print 5.0/22 (if you know the numbers absolutely)
  • print float(x)/22 (if you need to work with a variable integer x)
  • Just to extend the question, what about dividing by really large numbers like float(1)/(2**100). I still get zero – Eddy Zavala Oct 02 '18 at 19:56
0

Right now you're casting the result of integer division (5/22) to float. 5/22 in integer division is 0, so you'll be getting 0 from that. You need to call float(5)/22.

dpwilson
  • 997
  • 9
  • 19