Convert string fraction to decimal
Date: April 1st 2016
Last updated: April 1st 2016
The reason for doing this is to modify the string entries stored in a MySQL database (see getting started with MySQL).
python shell
from fractions import Fraction
f = '2/3'
Fraction(f)
#Fraction(2, 3)
float(Fraction(f))
#0.6666666666666666
function to split a string and convert to decimal
f = '2 2/8'
# Function should equal 2.25
def convert_my_string_to_float(value):
"""
Assume each string can only have one integer
and one fraction separated by a space
"""
mylist = value.split()
if len(mylist) > 1:
my_whole_number = float(mylist[0])
my_fraction = float(Fraction(mylist[1]))
myvalue = my_whole_number + my_fraction
return myvalue
else:
my_whole_number = float(mylist[0])
return my_whole_number
convert_my_string_to_float(f)
#2.25
function to convert feet to decimal
f = '2 9'
# Function should equal 2.75
def convert_feet_to_float(value):
"""
Assume each string can has two integers separated by a space
The first integer is feet (return as float)
The second integer is inches from 1 to 11
"""
mylist = value.split()
my_feet = float(mylist[0])
my_inches = float(int(mylist[1]) / 12)
myvalue = my_feet + my_inches
return myvalue
convert_feet_to_float(f)
#2.75