pythonpython-2.x

Convert fraction to decimal in Python


I want to convert 1/2 in python so that when i say print x (where x = 1/2) it returns 0.5

I am looking for the most basic way of doing this, without using any split functions, loops or maps

I have tried float(1/2) but I get 0... can someone explain me why and how to fix it?

Is it possible to do this without modifying the variable x= 1/2 ?


Solution

  • 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 built-in fraction type, but there is one in Python's standard 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...