Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a number is int or float

Tags:

types

perl

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?

like image 882
Alphaneo Avatar asked Nov 04 '10 05:11

Alphaneo


1 Answers

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.

like image 61
Sinan Ünür Avatar answered Sep 22 '22 02:09

Sinan Ünür