I have a two lists with values that I want to compare. If the value can be converted to a float, I want to compare the floats else I just want to compare the values as strings. How can I make that distinction to check whether a value can be converted to float or not?
1 Answer
The easiest way should be to just try to convert them to floats, and if that fails, fall back to a compare on strings:
def floatstrcmp(left, right):
try:
return cmp(float(left), float(right))
except ValueError:
return cmp(left, right)
2 Comments
whatnick
Always be careful when comparing floats !! Floats are inaccurate by nature and exact float comparison will fail if the said floats are calculations results.
Denis Otkidach
Note, that
float(obj) can raise TypeError (e.g. None) and AttributeError (python class instance) in addition to ValueError.