2

What is the easiest way to find out in Rails 3 whether a string str contains a positive float number or not ? (str is not an attribute in an active-record model)

It should work like this:

str = "123"         =>     true
str = "123.456"     =>     true
str = "0"           =>     true
str = ""            =>     false
str = "abcd"        =>     false
str = "-123"        =>     false
Phrogz
  • 296,393
  • 112
  • 651
  • 745
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
  • Duplicate of http://stackoverflow.com/questions/1034418/determine-if-a-string-is-a-valid-float-value (for Floats) and http://stackoverflow.com/questions/4282273/does-ruby-1-9-2-have-an-is-a-function/4282299 (For Integers) . BTW, `123` isn't a Float, it's an Integer. – Andrew Grimm Dec 27 '10 at 23:36

2 Answers2

7

Here's one idea:

class String
  def nonnegative_float?
    Float(self) >= 0
  rescue ArgumentError
    return false
  end
end

However, since you already seem to have a pretty good idea of what a nonnegative float number looks like, you could also match it against a Regexp:

class String
  def nonnegative_float?
    !!match(/\A\+?\d+(?:\.\d+)?\Z/)
  end
end
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • Note that this disallows `.123`; while this is invalid as a Ruby literal float, I suspect this may commonly occur in user input. – Phrogz Dec 27 '10 at 14:30
  • 3
    @Phrogz: Unfortunately, the OP's requirements specification is *incredibly* vague and his test coverage isn't exactly great, either, so it's basically guesswork. You assume that `'.123'` is valid, even though there is no test case for it. I assume that `'+123'` is valid and `' 123 '` is not, even though there are no test cases for it. A better answer would basically require a better question. – Jörg W Mittag Dec 27 '10 at 15:05
0

You can match it against a regular expression.

str === /^\d+(\.\d+)?$/
edgerunner
  • 14,873
  • 2
  • 57
  • 69