-
is_numeric
Posted on August 8th, 2009 3 commentsThe is_numeric() function allows you to check if a particular variable is a numeric string. Numeric strings can consist of a sign, any number of digits, a decimal part and an exponential part.
PHP
$my_string = '+1.998'; var_dump( is_numeric($string1) ); // => true
Ruby
def is_numeric?(num) true if Float(num) rescue false; end my_string = '+1.985'; puts is_numeric?(my_string); # => true
3 responses to “is_numeric”
-
ruby -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [i686-linux]>> “1a”.is_a?(Numeric)
=> false
>> “1″.is_a?(Numeric)
=> falsethis info is not correct, do we have to define our own function. please test your code before publishing it!!
-
@jef
Your right, there are some situations where the above code doesnt work - I’ve updated it with a slightly more robust function:
def is_numeric?(num)
true if Float(num) rescue false;
endmy_string = '1';
puts is_numeric?(my_string); -
Mike DiGioia April 20th, 2010 at 18:06
class String
def is_numeric?
self.strip =~ /^(-|\+|)[0-9]*(\.[0-9]+)?$/
end
endp ‘123′.is_numeric?
Leave a reply
-


