Check if the value is integer

4

I use the following code in php to check if the number is integer:

$qtd_bo = "1.20";

if (!preg_match('/^[1-9][0-9]*$/', $qtd_bo)) {
    echo "Não é inteiro";
}

It returns me that number 1.20 is not integer. Until then, okay.

The problem is that if I put 1.00 it tells me that it is not integer.

I need to check if there is any value after the "."

    
asked by anonymous 03.10.2016 / 15:37

3 answers

7

The value 1.00 will always be considered a float , however you can validate it as follows:

$value = "1.00";
return floor($value) != $value;

If the value in float actually is an "integer", the condition will return TRUE , because PHP compares the values without taking into account the type and function floor returns just the whole part, just.

    
03.10.2016 / 15:45
2

Number 1 is int but 1.0 is not int , it is float or it can also be double or decimal depending on the language. Did you understand the difference?

So 1.0 or 1.0000, will never be a int .

Test with a test

$str = 1.00;
var_dump(gettype($str)); // retorna double
var_dump(is_int($str)); // retorna false



An addendum, beware of this regular expression, since -1 is an integer, but the expression returns false:

if (!preg_match('/^[1-9][0-9]*$/', $str)) {
    echo 'não é inteiro';
}

Testing negative integer

$str = -1;
var_dump(gettype($str)); // retorna integer
var_dump(is_int($str)); // retorna true

link

link

    
03.10.2016 / 15:51
1

If you want to do with regex :

<?php

    $testes = array('-65','065','16as321','132,16','16544.01','-1');

    foreach ( $testes as $valor ){
        printf( "%s %s um número inteiro\n" , $valor , preg_match( '/^\-?[1-9][0-9]*$/' , $valor ) ? 'é' : 'não é' );
    }

?>

See working at Ideone .

In PHP , there is is_int , which informs if the variable is of the integer type.

<?php
   if (is_int(23)) {
      echo "is integer\n";
   } else {
      echo "is not an integer\n";
   }
   var_dump(is_int(23));
   var_dump(is_int("23"));
   var_dump(is_int(23.5));
   var_dump(is_int(true));
?>
    
03.10.2016 / 15:45