Determine if a string is numeric: Difference between revisions

m
Spelling/grammar/aesthetics, removed extra links
(→‎{{header|J}}: Minor code simplification.)
m (Spelling/grammar/aesthetics, removed extra links)
Line 91:
 
=={{header|C}}==
Returns true (non-zero) if character-string parameter represents a signed or unsigned integer. Otherwise returns false (zero).
Otherwise returns false (zero).
 
#include <stdlib.h>
Line 346 ⟶ 345:
Quoting from [http://perldoc.perl.org/perlfaq4.html#How-do-I-determine-whether-a-scalar-is-a-number%2fwhole%2finteger%2ffloat%3f perlfaq4]:
 
''How do I determine whether a [[scalar]] is a number/whole/integer/float?''
 
Assuming that you don't care about [[IEEE]] notations like "NaN" or "Infinity", you probably just want to use a [[regular expression]].
Line 359 ⟶ 358:
{ print "a C float\n" }
 
There are also some commonly used modules for the task. [[Scalar::Util]] (distributed with 5.8) provides access to perlPerl's internal function "looks_like_number" for determining whether a variable looks like a number. Data::Types exports functions that validate data types using both the above and other regular expressions. Thirdly, there is "Regexp::Common" which has regular expressions to match various types of numbers. Those three modules are available from the CPAN.
 
If you're on a [[POSIX]] system, Perl supports the "[[POSIX::strtod]]" function. Its semantics are somewhat cumbersome, so here's a "getnum" wrapper function for more convenient access. This function takes a string and returns the number it found, or "[[undef]]" for input that isn't a C float. The "is_numeric" function is a front end to "getnum" if you just want to say, ''Is this a float?''
 
sub getnum {
Line 379 ⟶ 378:
sub is_numeric { defined getnum($_[0]) }
 
Or you could check out the String::Scanf module on the CPAN instead. The POSIX module (part of the standard Perl distribution) provides the "strtod" and "strtol" for converting strings to double and longs, respectively.
 
=={{header|PHP}}==
Anonymous user