Re: how to check if string is a valid number

Re: how to check if string is a valid number

Good call on the negative numbers! Glad someone caught that!

On a related note the to_f and to_i methods are almost too good. If it can't parse something it returns either 0 or the components of it that it could figure out. That leads to ambiguous results since "ASDFasdfasfd".to_i returns 0 instead of nil or raising an exception.

So explicitly creating a Float is twice as slow as converting to an integer or float and back to a string.I also ran this with all values that would return false and got more of a 3 times slowdown, so I wonder if it has more to do with exception handling than object creation?

The result is:1.925948 is_numeric?3.642966 is_number?1.608794 is_a_number?(yep, my machine is slightly faster )The latter sub is the fastest one. You can win 10% more by removing to_s, but this is dangerous.

Re: how to check if string is a valid number

I know this thread is kind of old now, but I'd like to point out that the regular expression method of detection shown above does not correspond completely with the Float() method. Specifically, calling: