Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to recognize an int or a float

Status
Not open for further replies.
Jan 21, 2004
12
CA
Hi All,

I'm actually embarassed to ask this.

I would like to know how can I know if the var is
an integer or a float

my $a = 1234;
my $b = 0.1

I would like something like this :

if ($a is an integer)
{
# code
}
elsif ($b is a float)
{
# code
}
else
{
# code
}

All help is appreciated.

Thanks a hole bunch !
 
How about using pattern matching?
Code:
if ($a =~ /\./) {
    # $a has a decimal point

} else {
    # $a is an integer
}
 
For the float, I thought about that but then I ran into a problem :

$a = '1.a';

pattern macthing wont help in this case.

Isn't there someting like

if ($a =~ /0-9/) or if ($a =~ [0-9]) or if ($a =~ /[0-9]/)

that I can use ??
 
Hi All,

I made this for my int problem :

my $a = 1234;

my $R = VerifyInt($a);

if ($R == 1)
{
# its an integer
}

sub VerifyInt
{
my @Int = split(//, $_[0]);

foreach (@Int)
{
if (/[0-9]/)
{
next;
}
else
{
return 0;
}
}

return 1;
}

If anyone has a better way, please let me know.

for the float its the same thing execpt it looks for a decimal point as the first or second character and makes sure its there only once.
 
Here's another way:
Code:
sub VerifyInt($);
$a = '88.0.5';
$R = VerifyInt($a);
if ($R == 0) {
    print "$a is not a valid number \n";
} elsif ($R == 1) {
    print "$a is an integer\n";
} else {
    print "$a has a decimal point\n";
}

sub VerifyInt($) {
    $Number = "@_";
    $NumDecPoint++ while ($Number =~ /\./g);
    $NumDigit++ while ($Number =~ /\d/g);
    $NumNonDigit++ while ($Number =~ /\D/g);
    print "$NumDigit $NumDecPoint $NumNonDigit\n";
    if ($NumDigit < 1 or $NumDecPoint > 1 or $NumNonDigit > $NumDecPoint) {
        return(0)
    }
    if ($NumDecPoint > 0) {
        return(2);
    } else {
        return(1);
    }
}
 
Here's an alternative:
Code:
sub VerifyInt {
   my $int = shift;
   if(my ($fraction) = $int =~ /^\d+(\.\d+)?$/) {
      return $fraction?2:1;
   }
   else {
      return 0;
   }
}
 
Thanks guys,

Now all I have to do is benchmark the 3 subs and see which one is more faster and less memory hogger.

I will let you know the results.
 
@data = ('1234',
'0.1',
'.345',
'abc.345',
'1.a');

foreach (@data) {
if ($_ eq int($_)) {
print "$_ is an integer\n";
} elsif ($_ =~ m|^(\d+)?\.\d+$|) {
print "$_ is a float\n";
} else {
print "$_ is not a number at all!\n";
}
}


Kind Regards
Duncan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top