views:

89

answers:

3

Hello,

I want to simply check if a returned value from a form text field is a number i.e, 12 , 12.5, 12.75

is there a simple way to check, especially if the value is pulled as a param.

Thank you

+1  A: 

You can use

12.is_a? Fixnum

(Fixnum will work for ints 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).

Peter
based on the title, I thought this was for ruby (not rails)...
Peter
Sorry, this is Ruby on Rails ...Basically, I just want to be able to evaluate any input from the user whether it be .03 0.3, 2.2THe latter two work, but I need to get the first input working :S
+3  A: 

You can add a:

validates_numericality_of :the_field

in your model.

See: http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M002172

ryanprayogo
+1  A: 

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

v =~ /^[-+]?[0-9]*\.?[0-9]+$/
cwninja