Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a value is a number?

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?

like image 817
user211662 Avatar asked Jan 19 '10 17:01

user211662


People also ask

How do you check if a value is a number Python?

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 .

How do you check if a string is a number in JS?

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.


2 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).

like image 99
Peter Avatar answered Sep 26 '22 07:09

Peter


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 
like image 25
daesu Avatar answered Sep 24 '22 07:09

daesu