Python Convert Fraction to Decimal

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

I am looking for the easiest way to do this without using any shared functions, loops or maps

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

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

thanks

+9
python
source share
6 answers

in python 3.x, any unit returns a float;

>>> 1/2 0.5 

in order to achieve this in python 2.x, you need to force the float conversion:

 >>> 1.0/2 0.5 

or import unit from the "future"

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

Additionally: there is no built-in type of fractions, 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 

etc.

+25
source share

You are probably using Python 2. You can "fix" the separation using:

 from __future__ import division 

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

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

+7
source share

Alternatively, you can forcefully divide a floating point number by specifying a decimal, or multiply by 1.0. For example (from 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 before the strike at the time it took to dial my answer :)

+6
source share

If the input is a string, you can use Fraction directly at 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 
+5
source share

No 1/2 quantity anywhere. Python is not a rational number with a built-in type - just integers and floating point numbers. 1 is divided by 2 - after integer division rules - as a result of 0. float(0) is 0.

+3
source share

acbzxVxzzzCzCZCZCZCzCffddsfasvdbvscvxz

-7
source share

All Articles