How can I check if a value is a number?

Viewed 108207

I want to simply check if a returned value from a form text field is a number i.e.: 12 , 12.5 or 12.75. Is there a simple way to check this, especially if the value is pulled as a param?

9 Answers

You can use

12.is_a? Numeric

(Numeric will work for integers and floats.)

If it arrives as a string that might contain a representation of a valid number, you could use

class String
  def valid_float?
    true if Float self rescue false
  end
end

and then '12'.valid_float? will return true if you can convert the string to a valid float (e.g. with to_f).

Just regexp it, it's trivial, and not worth thinking about beyond that:

v =~ /\A[-+]?[0-9]*\.?[0-9]+\Z/

(Fixed as per Justin's comment)

Just convert string twice:

num = '12'
num == num.to_i.to_s 
#=> true 

num = '3re'
num == num.to_i.to_s 
#=> false

There was answer with Kernel#Float

But this variant is used with exception: false key and double bang to return boolean

class String
  def number?
    !!Float(self, exception: false)
  end
end
Related