1

I want to print a double in Python. But it doesn't work, and I don't know why.

My code:

test = 3000 / (1500 * 2000)
print str(test)

I always get a 0 and not a 0.001 even if I do the following:

test = 3000 / (1500 * 2000)
print '%.10f' % test

I get a 0.000000000 and not 0.001.

How do I tell Python that this should be a double?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
gurehbgui
  • 14,236
  • 32
  • 106
  • 178

3 Answers3

5

In Python 2.x you need to convert at least one of the operands to float, as integer division results in truncated output in Python 2.x:

>>> 3000 / (1500 * 2000)
0
>>> 3000.0 / (1500 * 2000) # Or use float(3000)
0.001
>>> float(3000) / (1500 * 2000)
0.001

Or you can import division of Python 3.x in Python 2.x, where integer division results in true division:

>>> from __future__ import division
>>> 3000.0 / (1500 * 2000)
0.001

Note that this will affect the division in the whole module.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
4

That's because you only used integer values at the math operation. Thus the result will be a (truncated) integer. If you want a float result, involve at least one float operand.

pram
  • 1,484
  • 14
  • 17
0

This behavior is fixed in Python 3.x. As pointed out in the other answers, the fix is to cast the divisible number to float.

If you want to make the / work as in Python 3.x, then you could do: from __future__ import division, and then you'll need to use the // operator to achieve the old behavior. You can check the Python documentation for information about operators.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jordan Jambazov
  • 3,460
  • 1
  • 19
  • 40