Tirth Jain
Tirth Jain

Reputation: 25

Check if string is float expressed as a decimal number only

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

Upvotes: 2

Views: 1830

Answers (1)

user2390182
user2390182

Reputation: 73450

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

Upvotes: 2

Related Questions