0

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
  • 3
    What have tried? What code do you have so far? This is not "do my homework.com". Commented Nov 20, 2009 at 15:55

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Always be careful when comparing floats !! Floats are inaccurate by nature and exact float comparison will fail if the said floats are calculations results.
Note, that float(obj) can raise TypeError (e.g. None) and AttributeError (python class instance) in addition to ValueError.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.