2

I'm writing script for checking if a pair of numbers is a valid coordinate. I need to check if the numbers are expressed as decimals only and in the range of 0 to 180 positive or negative for longitude and 0 to 90 positive or negative for latitude. I have used a try/except block to check if the number is a float like this:

def isFloat(n):
    try:
       float(n)
       return True
    except ValueError:
       return False

While this mostly works, I want it to accept floats expressed only as decimals and not values like True, False, 1e1, NaN

1
  • surprisingly this is not a duplicate! +1!! Commented Jan 29, 2017 at 16:50

1 Answer 1

2

You could use a fairly simple regular expression:

import re

def isFloat(n):
    n = str(n)  # optional; make sure you have string
    return bool(re.match(r'^-?\d+(\.\d+)?$', n))  # bool is not strictly necessary
    # ^         string beginning
    # -?        an optional -
    # \d+       followed by one or more digits (\d* if you want to allow e.g. '.95')
    # (\.\d+)?  followed by an optional group of a dot and one or more digits
    # $         string end

>>> isFloat('4')
True
>>> isFloat('4.567')
True
>>> isFloat('-4.567')
True
>>> isFloat('-4.')
False
>>> isFloat('-4.45v')
False
>>> isFloat('NaN')
False
>>> isFloat('1e1')
False
Sign up to request clarification or add additional context in comments.

4 Comments

I would change the first d+ to d* to catch values like .985. Also, while I think this solution is the best for the poster's needs, it does require n to be (cast to) a string.
I'm afraid I'm just a novice so could you please explain how this works?
@TirthJain I added some explanation and added the link to the docs of pythons regex module. As for the ins and outs of regular expression syntax, you should read the docs or do a tutorial ;)
@huck_cussler I added that option in the comment, but I don't really like it as it would accept the empty string... (without further complicating the expression) As for the casting, I took it from the question's title that n is a string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.