Python Parse Percentage String to Float

July 25, 2019
def parse_float(value):
    try:
        return float(value)
    except ValueError:
        if value.endswith('%'):
            return float(value[:-1])/100
        raise ValueError(f"Unknown float value: {value}")

Usage

value = parse_float("0.052")    # 0.052
value = parse_float("5.2%")     # 0.052
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.