11

Is there any difference between floor() and intval()? Though both returns the same results, is there any issue with regard to performance? Which of the two is faster? Which is the right php function to use if I just want to return the whole value only of a decimal?

The goal here is to display 1999.99 to 1999, omitting the decimal value and only return the whole number.

$num = 1999.99;
$formattedNum = number_format($num)."<br>";
echo intval($num) . ' intval' . '<br />';
echo floor($num) . ' floor';
2
  • 1
    NOT the same results: var_dump( intval($num) ); var_dump( floor($num) ); also check var_dump( intval(-$num) ); var_dump( floor(-$num) ); Commented Apr 28, 2016 at 20:19
  • 1
    intval() discards the decimal portion, and returns an integer. floor() rounds down, and returns a float.
    – Sammitch
    Commented Apr 28, 2016 at 20:36

6 Answers 6

21

The functions give different results with negative fractions.

echo floor(-0.1); // -1
echo intval(-0.1); // 0
2
  • Now I see the difference. It seems that float rounds it when a negative number while the intval extract the whole number (which is what I wanted to display)
    – basagabi
    Commented Apr 28, 2016 at 20:27
  • 1
    @basagabi floor() doesn't round it. It returns the nearest integer which is less than the given value Commented Jun 19, 2020 at 15:29
6

The fastest way is to use type casting: (int)$num.

5

Per the docs,

The return value of floor() is still of type float because the value range of float is usually bigger than that of integer.

Intval() returns an int, however.

0
$v = 1999.99;
var_dump(
  intval($v),
  floor($v)
);

Output:

int(1999)
float(1999)

Docs:

http://php.net/manual/en/function.intval.php
http://php.net/manual/en/function.floor.php

0

There is more to this answer. In the specific use case of 1999.99, the 2 functions will give the same results numerically. However, as others have noted, intval return as int and floor returns it as a float. I am not clear why floor returns as float as it is not necessary. Also, as others have noted, intval simply chops off the decimal where floor returns the "lowest" integer, which impacts negative numbers.

For the remaining difference is that intval will accept way many more variable types and attempt to return a logical answer where floor expects only integer or float. For example, if false or true is fed into floor, you will get an error, but intval will convert it to 0 and 1 respectively.

-1
$ratio_x = (0.70/100);

$computation =  $ratio_x * 8000;

$noDeci = floor(($ratio_x * 8000)*1)/1;

$intval = intval(($ratio_x * 8000)*1)/1;

$noDeci_hc = floor((int)56*1)/1;

echo $computation."|".$noDeci."|".$noDeci_hc."|".$intval;

OUTPUT: 56|55|56|55

$noDeci returns 55???

Not the answer you're looking for? Browse other questions tagged or ask your own question.