Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP check if is integer

Tags:

php

isinteger

I have the following calculation:

$this->count = float(44.28)
$multiple = float(0.36)
$calc = $this->count / $multiple;
$calc = 44.28 / 0.36 = 123

Now I want to check if my variable $calc is integer (has decimals) or not.

I tried doing if(is_int()) {} but that doesn't work because $calc = (float)123.

Also tried this-

if($calc == round($calc)) 
{ 
   die('is integer');
} 
else 
{
   die('is float);
}

but that also doesn't work because it returns in every case 'is float'. In the case above that should'n be true because 123 is the same as 123 after rounding.

like image 217
Joachim Vanthuyne Avatar asked Mar 24 '14 10:03

Joachim Vanthuyne


4 Answers

Try-

if ((string)(int) $calc === (string)$calc) {
  //it is an integer
}else{
  //it is a float
}

Demo

like image 103
Sahil Mittal Avatar answered Sep 28 '22 01:09

Sahil Mittal


As CodeBird pointed out in a comment to the question, floating points can exhibit unexpected behaviour due to precision "errors".

e.g.

<?php
$x = 1.4-0.5;
$z = 0.9;

echo $x, ' ', $z, ' ', $x==$z ? 'yes':'no';

prints on my machine (win8, x64 but 32bit build of php)

0.9 0.9 no

took a while to find a (hopefully correct) example that is a) relevant to this question and b) obvious (I think x / y * y is obvious enough).

again this was tested on a 32bit build on a 64bit windows 8

<?php
$y = 0.01; // some mambojambo here... 
for($i=1; $i<31; $i++) { // ... because ...
    $y += 0.01; // ... just writing ...
} // ... $y = 0.31000 didn't work

$x = 5.0 / $y;
$x *= $y;

echo 'x=', $x, "\r\n";
var_dump((int)$x==$x);

and the output is

x=5
bool(false)

Depending on what you're trying to achieve it might be necessary to check if the value is within a certain range of an integer (or it might be just a marginalia on the other side of the spectrum ;-) ), e.g.

function is_intval($x, $epsilon = 0.00001) {
    $x = abs($x - round($x));
    return $x < $epsilon;
};

and you might also take a look at some arbitrary precision library, e.g. the bcmath extension where you can set "the scale of precision".

like image 33
VolkerK Avatar answered Sep 28 '22 01:09

VolkerK


You can do it using ((int) $var == $var)

$var = 9;
echo ((int) $var == $var) ? 'true' : 'false';
//Will print true;
$var = 9.6;
echo ((int) $var == $var) ? 'true' : 'false';
//Will print false;

Basically you check if the int value of $var equal to $var

like image 21
darkheir Avatar answered Sep 28 '22 01:09

darkheir


round() will return a float. This is because you can set the number of decimals.

You could use a regex:

if(preg_match('~^[0-9]+$~', $calc))

PHP will convert $calc automatically into a string when passing it to preg_match().

like image 23
hek2mgl Avatar answered Sep 28 '22 03:09

hek2mgl