Check that the value is integer

Asked

Viewed 4,603 times

5

Galera use the following code in php to check that the number is integer:

$qtd_bo = "1.20";

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

It returns to me that the number 1.20 is not integer. Until then ok.

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

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

3 answers

8


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

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

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

  • very good, my code went like this : if (floor($value) != $value) {
 echo "Não é inteiro";
}

  • Perfect, simple right...

2

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 on Ideone.

In the PHP, there is the is_int, which informs whether 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));
?>

2

The number 1 is int but 1.0 is not int, is a float or may also be double or decimal depending on the language. Understood the difference?

So 1.0 or 1.0000, will never be a int.

Check 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, for -1 is an integer, but the expression returns false:

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

Testing negative integer number

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

http://php.net/manual/en/language.types.integer.php

http://php.net/manual/en/language.types.float.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.