8

I am attempting to do what should be very simple and check to see if a value in an Entry field is a valid and real number. The str.isnumeric() method does not account for "-" negative numbers, or "." decimal numbers.

I tried writing a function for this:

def IsNumeric(self, event):
    w = event.widget
    if (not w.get().isnumeric()):
        if ("-" not in w.get()):
            if ("." not in w.get()):
                w.delete(0, END)
                w.insert(0, '')

This works just fine until you go back and type letters in there. Then it fails.

I researched the possibility of using the .split() method, but I could not figure out a reliable regex to deal for it.

This is a perfectly normal thing that needs to be done. Any ideas?

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
texasman1979
  • 473
  • 1
  • 6
  • 17

3 Answers3

19
try:
    float(w.get())
except ValueError:
    # wasn't numeric
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • If i had a brain I would have thought of that. There is no reason that cant be wrapped in an IsNumeric function. :) – texasman1979 Jun 15 '15 at 21:52
3

It sounds like you might just need to know whether passing some string to float will give a result (i.e. it is a nice numeric value), or an error (i.e. the string doesn't represent a number). Try this:

def isnum(s):
    try:
        float(s)
    except:
        return(False)
    else:
        return(True)
tegancp
  • 1,204
  • 6
  • 13
  • 4
    Catching everything with a bare `except` is a bad idea. You also do not need parenthesis around `False` and `True`. – Ethan Furman Jun 15 '15 at 21:55
0

I realise this is an old question but I've just faced this problem. You can do something like:

if re.sub("[^0-9\\-\\.]", "", "-0.18"):
Richard
  • 1,070
  • 9
  • 22