is that string a number? (in ruby)

sometimes it’s nice to determine if the content of a String is numeric. String#to_i and String#to_f don’t really help because they’ll silently coerce stuff into zero (e.g., “huned”.to_i # => 0). so here’s a little thing i built a long time ago. i updated it today to handle commas and parenthesis, which are often used in financial data.

class Regexp
  NUMERIC = Regexp.union(%r{^-?\d{1,3}(,\d{3}|\d+)*(\.\d+)*$},
    %r{^\(?\d{1,3}(,\d{3}|\d+)*(\.\d+)*\)?$})
end

class String
  def numeric?
    match(Regexp::NUMERIC) != nil
  end
end

examples!

  • “1.234″.numeric? # => true
  • “1,234,567″.numeric? # => true
  • “1,234,567.23583″.numeric? # => true
  • “1234567″.numeric? # => true
  • “(1,234)”.numeric? # => true
  • “-1,234″.numeric? # => true
  • etc

it works, but i’m not totally happy with the regular expression. who has a better one?


About this entry