validity test for Float

Discussion in 'Ruby' started by Craig, May 28, 2006.

  1. Craig

    Craig Guest

    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
    Craig, May 28, 2006
    #1
    1. Advertising

  2. Craig

    Sammyo Guest

    You could consider converting to a appropriate base:

    >> a = "mambo".to_i(base=23).to_f

    => 273481.0

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

    Oh, and for the too literal -> :) :)
    Sammyo, May 28, 2006
    #2
    1. Advertising

  3. Craig

    Craig Guest

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

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Andy
    Replies:
    7
    Views:
    6,239
    Roedy Green
    May 10, 2004
  2. bd
    Replies:
    0
    Views:
    605
  3. Replies:
    0
    Views:
    263
  4. Skybuck Flying

    Call oddities: &Test() vs &Test vs Test

    Skybuck Flying, Oct 4, 2009, in forum: C Programming
    Replies:
    1
    Views:
    682
    Skybuck Flying
    Oct 4, 2009
  5. Carsten Fuchs
    Replies:
    45
    Views:
    1,505
    James Kanze
    Oct 8, 2009
Loading...

Share This Page