Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

fraction to float

def convert_to_float(frac_str):
    try:
        return float(frac_str)
    except ValueError:
        num, denom = frac_str.split('/')
        try:
            leading, num = num.split(' ')
            whole = float(leading)
        except ValueError:
            whole = 0
        frac = float(num) / float(denom)
        return whole - frac if whole < 0 else whole + frac


print convert_to_float('3') # 3.0
print convert_to_float('3/2') # 1.5
print convert_to_float('1 1/2') # 1.5
print convert_to_float('-1 1/2') # -1.5
Comment

PREVIOUS NEXT
Code Example
Python :: Python NumPy stack Function Example with 2d array 
Python :: python vim auto indent on paste 
Python :: data types in numpy array 
Python :: pip in python 
Python :: aiohttp 
Python :: python How do you find the middle element of a singly linked list in one pass? 
Python :: split() vs split() 
Python :: pandas mean of n columns 
Python :: check this id exist in database django 
Python :: pytesseract.image_to_data(img output_type=output.dict) 
Python :: cascaed models in django 
Python :: Palindrome in Python Using while loop for string 
Python :: append to list at index python 
Python :: how to make a new column with explode pyspark 
Python :: how to specify root geometry in tkinter 
Python :: max in python 
Python :: change a decimal to time in datetime python 
Python :: django change foreign key 
Python :: repl.it secret 
Python :: protected vs private python 
Python :: pandas remove multi header from dataframe 
Python :: python argparse option groups 
Python :: recursion python examples 
Python :: dictionary increment 
Python :: select statement python 
Python :: python file get text by regular expression 
Python :: different types f python loops 
Python :: how to create a User and User profile in django rest framework 
Python :: python autoclick website 
Python :: Python Tkinter CheckButton Widget Syntax 
ADD CONTENT
Topic
Content
Source link
Name
6+1 =