vindaloo has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I am looking for the best way to test for a float. I am using something like this:
my $var = 2.5; if (int($var) != $var) { print "Is a float\n"; }
It is not always working though. Is there a standard and tested way to test for a float in Perl?

Replies are listed 'Best First'.
Re: dependable way to test for a float
by davidrw (Prior) on May 04, 2005 at 23:43 UTC
    You can test with a regexp, which you can roll your own with something like (this is a fairly simple example):
    if ( $var =~ /^-?\d+(\.\d+)?$/ ){ # you have a float }
    But I'd recommend checking out Regexp::Common::number which will cover many more cases.
Re: dependable way to test for a float
by Thelonious (Scribe) on May 05, 2005 at 07:44 UTC
    use Scalar::Util::Numeric qw(isfloat); my $var = shift || 0E0; print "'$var' is "; print "not " unless isfloat($var); print "a float\n";
Re: dependable way to test for a float
by shemp (Deacon) on May 04, 2005 at 23:43 UTC
    From the perl cookbook section 2.1, with my own reformatting and comments:
    sub isThisADecimalNumber { my ($string) = @_; return $string =~ /^\s* -? # negative sign - optional (?: \d+ # digits (?:\.\d*)? # and an optional decimal and +maybe more digits | # OR \.\d+ # a decimal and some digits ) \s*$/x; }
      An optional decimal would not be a float, so I think this is not testing for a float.
        I see your point. My test is more to check if a string is numeric or not, not exactly is this number a float.
Re: dependable way to test for a float
by Roy Johnson (Monsignor) on May 04, 2005 at 23:34 UTC
    When doesn't it work? What do you want to differentiate a float from?

    Caution: Contents may have been coded under pressure.

      I have not totally isolated when it does not work yet. I am testing for a floating point number to separate from both booleans and strings all of which are values in a hash.

      I just had deja vu writing this....yet no recollection of doing this in a past life.

        For your purposes, are the integers not floats? I can't think of any case where the int($n) != $n test wouldn't work. Or would it be a float if it were '0.0' (for example)?

        Though you haven't isolated when it doesn't work, can you give any example for which it doesn't work?


        Caution: Contents may have been coded under pressure.