views:

2753

answers:

8

For example, the standard division symbol '/' rounds to zero:

>>> 4 / 100
0

However, I want it to return 0.04. What do I use?

+1  A: 

Try 4.0/100

Martin Cote
+1  A: 

A simple route 4 / 100.0

or

4.0 / 100

torial
+2  A: 

You need to tell Python to use floating point values, not integers. You can do that simply by using a decimal point yourself in the inputs:

>>> 4/100.0
0.040000000000000001
moonshadow
+28  A: 

There are three options:

>>> 4 / float(100)
0.04
>>> 4 / 100.0
0.04

which is the same behavior as the C, C++, Java etc, or

>>> from __future__ import division
>>> 4 / 100
0.04

You can also activate this behavior by passing the argument -Qnew to the Python interpreter:

$ python -Qnew
>>> 4 / 100
0.04

The second option will be the default in Python 3.0. If you want to have the old integer division, you have to use the // operator.

Edit: added section about -Qnew, thanks to ΤΖΩΤΖΙΟΥ!

Torsten Marek
Please also add the availability of `python -Q new` command-line option to make your answer more complete.
ΤΖΩΤΖΙΟΥ
This gives a floating point value, not a decimal value. See Glyph's answer.
Jim
+4  A: 

Make one or both of the terms a floating point number, like so:

4.0/100.0

Alternatively, turn on the feature that will be default in Python 3.0, 'true division', that does what you want. At the top of your module or script, do:

from __future__ import division
Thomas Wouters
A: 

You cant get a decimal value by dividing one integer with another, you'll allways get an integer that way (result truncated to integer). You need at least one value to be a decimal number.

Vasil
Please note that this won't be the case anymore in Python 3.0 if you use /.
Torsten Marek
+9  A: 

Other answers suggest how to get a floating-point value. While this wlil be close to what you want, it won't be exact:

>>> 0.4/100.
0.0040000000000000001

If you actually want a decimal value, do this:

>>> import decimal
>>> decimal.Decimal('4') / decimal.Decimal('100')
Decimal("0.04")

That will give you an object that properly knows that 4 / 100 in base 10 is "0.04". Floating-point numbers are actually in base 2, i.e. binary, not decimal.

Glyph
+1  A: 

You might want to look at Python's decimal package, also. This will provide nice decimal results.

>>> decimal.Decimal('4')/100
Decimal("0.04")
S.Lott