tags:

views:

123

answers:

3

Is there some function like str.isnumeric but applicable to float?

'13.37'.isnumeric() #False  

I still use this:

def isFloat(string):
    try:
        float(string)
        return True
    except ValueError:
        return False
+2  A: 

Your code is absolutely fine. Regex based soultions are more likely to be error prone.

Quick testing with timeit reveals float(str_val) is indeed faster than re.match()

>>> timeit.timeit('float("-1.1")')
1.2833082290601467
>>> timeit.timeit(r"pat.match('-1.1')", "import re; pat=re.compile(r'^-?\d*\.?\d+(?:[Ee]-?\d+)?$');")
1.5084138986904527

And the regex used above fails one edge case, it can't match '-1.', although float() will happily convert it to proper float value.

Imran
I think I remember seeing a thread about this on a mailing list a long time ago. The gist was that float() and a regex were about the same speed.
Richard Levasseur
It's not a Python-way I think - 6 lines of code to solve common problem. But, thanks.
Andrew
Using re.compile will make the regexp pretty much the same speed as float().
truppo
@Imran: your performance comparison is not correct, while `float` would be faster, you need to compile regex outside of the execution loop, it needs to be re-used for that method to be practical.
SilentGhost
Performance with compiled regex is even worse :P. How could that be? The `setup` statement in `timeit.timeit` is eval'ed just once, isn't it?
Imran
gosh, you need to do `pat.match('1.1')`. Also `match` is always starting from the start of the subject string, no `^` required.
SilentGhost
@SilentGhost: Thanks, now regex's performance is lot closer to `float` :)
Imran
The regexp needs to also match floats written with an exponent, for example '10e-2'
Paul Hankin
@Paul: Updated the regex to match exponent
Imran
A: 

isinstance(myVariable, float) will work if you're testing a floating point variable.

Edit: Spoke too soon, didn't fully understand what you were trying to get.

echoback
that's not what OP wants
SilentGhost
+6  A: 

As Imran says, your code is absolutely fine as shown.

However, it does encourage clients of isFloat down the "Look Before You Leap" path instead of the more Pythonic "Easier to Ask Forgiveness than Permission" path.

It's more Pythonic for clients to assume they have a string representing a float but be ready to handle the exception that will be thrown if it isn't.

This approach also has the nice side-effect of converting the string to a float once instead of twice.

Jon-Eric
+1: @pingvinus: Please don't waste time writing such things. Just write your real application. If it throws a `ValueError` that means the input wasn't valid float and an overall exception handler can report this. There's no need to pre-check for float values, since the `float` function does this right when you need it. And always correctly.
S.Lott