Floating point problem

Peter Otten __peter__ at web.de
Fri Apr 17 07:29:19 EDT 2020


Aakash Jana wrote:

> I am calculating couple of ratios and according to the problem there must
> be a 6 decimal precision. But when I print the result I only get one 0.
> E.g:- 2 / 5 = 0.400000 but I am only getting 0.4

Make sure that you are using Python 3, not Python 2 or use at least one 
float operand:

# Python 3
>>> 2/5
0.4

# Python 2 and 3
>>> 2.0 / 5
0.4

You can get the old default behaviour with the // operator:

# Python 3 (and Python 2)
>>> 2//5
0
>>> 7//2
3

If for some reason you cannot switch to Python 3 you can add the line

from __future__ import division

at the top of your script or module. Then:

$ python
Python 2.7.6 (default, Nov 13 2018, 12:45:42) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import division
>>> 2 / 5
0.4




More information about the Python-list mailing list