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?
+4
A:
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)
sth
2009-11-20 15:56:26
Always be careful when comparing floats !! Floats are inaccurate by nature and exact float comparison will fail if the said floats are calculations results.
whatnick
2009-11-20 16:44:02
Note, that `float(obj)` can raise TypeError (e.g. None) and AttributeError (python class instance) in addition to ValueError.
Denis Otkidach
2009-11-20 16:54:35