in reply to Re: Re: How to check Inputs if Numeric
in thread How to check Inputs if Numeric

I know this thread is old but it came up on google firstish. I searched, then came up with my own line, which I think works better than the regexp. I did not check all over, so most likely it is already around somewhere.

if ( $input+0 eq $input ){ print "it is a number!\n";}

Can someone point out the problem with this approach? Advantage for me: easy + quick, no problems with signs...

Replies are listed 'Best First'.
Re^4: How to check Inputs if Numeric
by jdporter (Paladin) on Mar 07, 2014 at 02:58 UTC

    Depends on whether you'd consider "000" a number, for example. (I would, probably, in most cases.)

    I reckon we are the only monastery ever to have a dungeon stuffed with 16,000 zombies.
Re^4: How to check Inputs if Numeric (eq 0+)
by tye (Sage) on Mar 07, 2014 at 03:55 UTC

    Not bad, especially given the simplicity. More potential false negatives to go with jdporter's.

    for my $input (qw< +4 1.0 1e5 12345678901234567890 1.234567890123456789 >) { if( $input+0 eq $input ) { print "$input is a number!\n"; } else { print "$input is not ", 0+$input, "\n"; } } __END__ +4 is not 4 1.0 is not 1 1e5 is not 100000 12345678901234567890 is not 1.23456789012346e+019 1.234567890123456789 is not 1.23456789012346

    Update: It successfully detects if $input is (primarily) holding a numeric value (an IV or NV, how Perl stores an integer and floating point, respectively) or is holding a string value that equals the canonical string representation of any possible Perl numeric value.

    So I don't believe that there are any false positives. The false negatives are the many ways to reasonably represent a numeric value that aren't Perl's canonical representation.

    - tye        

Re^4: How to check Inputs if Numeric
by Anonymous Monk on Mar 16, 2014 at 11:52 UTC

    just a quick (final) note : ($nr+0 eq $nr ) is not perfect for checking on numbers in general, but it is a very good check for integer numbers.

    It avoids perl complaining about casting as some other methods would and is pretty easy on resources

Re^4: How to check Inputs if Numeric
by choroba (Cardinal) on Mar 16, 2014 at 16:11 UTC
    If you don't mind "nan" and "inf" among numbers...
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re^4: How to check Inputs if Numeric
by Anonymous Monk on Mar 08, 2014 at 20:00 UTC

    thanks for the replies!

    some of the problems pointed out would not bother me much IRL ( i.e. most of my applications ), the one with 1.0 for example would. Back to regexp's I suppose :/