In perl, I want to check if the given variable holds a floating point number of not. To check this I am using,
my $Var = 0.02 # Floating point number
if (int($Var) != $Var) {
# floating point number
}
But the above code will not work for 0.0,
How can I achieve this?
This is a FAQ. See How do I determine whether a scalar is a number/whole/integer/float?
You can also use Scalar::Util::Numeric.
Interestingly, while
#!/usr/bin/perl
use strict; use warnings;
use Scalar::Util::Numeric qw(isint);
my $x = 0.0;
print "int\n" if isint $x;
prints int
(not surprising if you look at the source code), based on @tchrist's comment, it should be possible to look at the information supplied in the variables structure to distinguish 0
from 0.0
:
#!/usr/bin/perl
use strict; use warnings;
use Devel::Peek;
my $x = 0.0; print Dump $x;
my $y = 0; print Dump $y;
$y *= 1.1; print Dump $y;
Output:
SV = NV(0x18683cc) at 0x182c0fc REFCNT = 1 FLAGS = (PADMY,NOK,pNOK) NV = 0 SV = IV(0x182c198) at 0x182c19c REFCNT = 1 FLAGS = (PADMY,IOK,pIOK) IV = 0 SV = PVNV(0x397ac) at 0x182c19c REFCNT = 1 FLAGS = (PADMY,NOK,pNOK) IV = 0 NV = 0 PV = 0
It seems to me that the check would have to just look at if the NOK
flag is set. It takes me ages to write even the simplest XS so I won't provide an implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With