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
?
Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .
Use the isNaN() Function to Check Whether a Given String Is a Number or Not in JavaScript. The isNaN() function determines whether the given value is a number or an illegal number (Not-a-Number). The function outputs as True for a NaN value and returns False for a valid numeric value.
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
).
I usually just use Integer and Float these days.
1.9.2p320 :001 > foo = "343" => "343" 1.9.2p320 :003 > goo = "fg5" => "fg5" 1.9.2p320 :002 > Integer(foo) rescue nil => 343 1.9.2p320 :004 > Integer(goo) rescue nil => nil 1.9.2p320 :005 > Float(foo) rescue nil => 343.0 1.9.2p320 :006 > Float(goo) rescue nil => nil
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With