Search code examples
pythonstringfloating-pointfloating-point-conversionfloating-point-exceptions

Cannot convert string to float


I am getting information from a csv, I need to take a field which in theory is a float, but can come empty, I'm this function which takes the row [i] where the float is, and should return the float,

def fun(x):
    if not(x):
        x=0
        x=float(x)
    else:
        x = float(x)
    return x

but when i try it throws me this error tells me "float () argument must be a string or a number"


Solution

  • Ok, how about

    def fn(x):
        try:
            return float(x)
        except (ValueError, TypeError):
            return 0.0