Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Conversion of number string to float in django

from fractions import Fraction


def number_str_to_float(amount_str):
    """
    Take in an amount string to return float (if possible).

    Valid string returns:
    Float
    Boolean -> True

    Invalid string Returns
    Original String
    Boolean -> False

    Examples:
    1 1/2 -> 1.5, True
    32 -> 32.0, True
    Abc -> Abc, False
    """
    success = False
    number_as_float = amount_str
    try:
        number_as_float = round(float(sum(Fraction(s)
                                for s in f"{amount_str}".split())), 2)
    except:
        pass
    if isinstance(number_as_float, float):
        success = True
    return number_as_float, success
Comment

PREVIOUS NEXT
Code Example
Python :: Write a Python function to check whether a number is in a given range. 
Python :: python pandas replace not working 
Python :: add column array python 
Python :: path of current working directory with os module python 
Python :: get python path 
Python :: change date format python code 
Python :: handle queries in listview django 
Python :: python test is nan 
Python :: python convert exponential to int 
Python :: Python Program to count the number of lowercase letters and uppercase letters in a string. 
Python :: random sample with weights python 
Python :: pandas slicing from one column to another 
Python :: how to import axes3d 
Python :: Python Tkinter TopLevel Widget Syntax 
Python :: write data to using pickle 
Python :: how to install whl file in python 
Python :: django login_required decorator 
Python :: date colomn to datetime 
Python :: python binary tree 
Python :: what does class meta do in django 
Python :: pandas index from 1 
Python :: get a colomn of csv in pandas 
Python :: corr pandas 
Python :: intersection between two arrays using numpy 
Python :: python check if number is in range 
Python :: exec: "python": executable file not found in $PATH Error compiling for board ESP32 Dev Module. 
Python :: curl in python 
Python :: pandas change to numeric 
Python :: jupyter markdown new line 
Python :: python letter to number in alphabet 
ADD CONTENT
Topic
Content
Source link
Name
4+9 =