Python Convert fraction to decimal

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 ??

Thanks

Answers


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 :)


If the input is a string,then you could use Fraction directly on the input:

from fractions import Fraction

x='1/2'
x=Fraction(x)  #change the type of x from string to Fraction
x=float(x)     #change the type of x from Fraction to float
print x

There is no quantity 1/2 anywhere. Python does not represent rational numbers with a built-in type - just integers and floating-point numbers. 1 is divided by 2 - following the integer division rules - resulting in 0. float(0) is 0.


Need Your Help

Unit-Testing: Database set-up for tests

c# database unit-testing

I'm writing unit-tests for an app that uses a database, and I'd like to be able to run the app against some sample/test data - but I'm not sure of the best way to setup the initial test data for the