validity test for Float

C

Craig

Q from a newbie:

Is there any way to test if a string is valid to pass to Float?

irb(main):025:0> Float( "2.0" )
=> 2.0
irb(main):026:0> Float( "mambo" )
ArgumentError: invalid value for Float(): "mambo"
from (irb):26:in `Float'
from (irb):26
irb(main):027:0> "2.0".to_f
=> 2.0
irb(main):028:0> "mambo".to_f
=> 0.0

to_f doesn't seem to do it, as it returns 0.0 even if the string is
invalid.

Many TIA,
Craig
 
S

Sammyo

You could consider converting to a appropriate base:
=> 273481.0

(not sure why a lower base didn't work)

Oh, and for the too literal -> :) :)
 
C

Craig

Thanks super! It works, but feels somewhat kludgy. It would be nice
to have some sort of String#isnum? as a built-in.
Craig
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top