Python Convert fraction to decimal

in python 3.x any division returns a float;

>>> 1/2
0.5

to achieve that in python 2.x, you have to force float conversion:

>>> 1.0/2
0.5

or to import the division from the "future"

>>> from __future__ import division
>>> 1/2
0.5

An extra: there is no a built-in fraction type, but there is in the official library:

>>> from fractions import Fraction
>>> a = Fraction(1, 2) #or Fraction('1/2')
>>> a
Fraction(1, 2)
>>> print a
1/2
>>> float(a)
0.5

and so on...


You're probably using Python 2. You can "fix" division by using:

from __future__ import division

at the start of your script (before any other imports). By default in Python 2, the / operator performs integer division when using integer operands, which discards fractional parts of the result.

This has been changed in Python 3 so that / is always floating point division. The new // operator performs integer division.


Alternatively, you can force floating point division by specifying a decimal or by multiplying by 1.0. For instance (from inside the python interpreter):

>>> print 1/2
0
>>> print 1./2
0.5
>>> x = 1/2
>>> print x
0
>>> x = 1./2
>>> print x
0.5
>>> x = 1.0 * 1/2
>>> print x
0.5

EDIT: Looks like I was beaten to the punch in the time it took to type up my response :)

Tags:

Python