Convert PHP code into Ruby!
RSS icon Email icon Home icon
  • is_numeric

    Posted on August 8th, 2009 RubyLove 3 comments

    The is_numeric() function allows you to check if a particular variable is a numeric string. Numeric strings can consist of a sign, any number of digits, a decimal part and an exponential part.

    PHP

    $my_string = '+1.998';
    var_dump( is_numeric($string1) );
    // => true

    Ruby

    def is_numeric?(num)
        true if Float(num) rescue false;
    end
     
    my_string = '+1.985';
    puts is_numeric?(my_string);
    # => true
     

    3 responses to “is_numeric”

    1. ruby -v
      ruby 1.8.7 (2008-08-11 patchlevel 72) [i686-linux]

      >> “1a”.is_a?(Numeric)
      => false
      >> “1″.is_a?(Numeric)
      => false

      this info is not correct, do we have to define our own function. please test your code before publishing it!!

    2. @jef

      Your right, there are some situations where the above code doesnt work - I’ve updated it with a slightly more robust function:


      def is_numeric?(num)
      true if Float(num) rescue false;
      end

      my_string = '1';
      puts is_numeric?(my_string);

    3. class String
      def is_numeric?
      self.strip =~ /^(-|\+|)[0-9]*(\.[0-9]+)?$/
      end
      end

      p ‘123′.is_numeric?

    Leave a reply