Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a decimal value when using the division operator in Python?

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

>>> 4 / 100 0 

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

like image 717
Ray Avatar asked Sep 22 '08 20:09

Ray


People also ask

How do you get the float value after division in Python?

To divide float values in Python, use the / operator. The Division operator / takes two parameters and returns the float division. Float division produces a floating-point conjecture of the result of a division. If you are working with Python 3 and you need to perform a float division, then use the division operator.

How do you use the division operator in Python?

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.


1 Answers

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 ΤΖΩΤΖΙΟΥ!

like image 183
Torsten Marek Avatar answered Sep 28 '22 11:09

Torsten Marek