Skip to content

Instantly share code, notes, and snippets.

@codingforentrepreneurs
Created August 5, 2021 16:20
Show Gist options
  • Select an option

  • Save codingforentrepreneurs/bcac6c1a047aec031f58984d5188e57d to your computer and use it in GitHub Desktop.

Select an option

Save codingforentrepreneurs/bcac6c1a047aec031f58984d5188e57d to your computer and use it in GitHub Desktop.

Revisions

  1. codingforentrepreneurs created this gist Aug 5, 2021.
    28 changes: 28 additions & 0 deletions number_str_to_float.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    from fractions import Fraction

    def number_str_to_float(amount_str:str) -> (any, bool):
    """
    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 = float(sum(Fraction(s) for s in f"{amount_str}".split()))
    except:
    pass
    if isinstance(number_as_float, float):
    success = True
    return number_as_float, success