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) ); Apr 28, 2016 at 20:19
  • 1
    intval() discards the decimal portion, and returns an integer. floor() rounds down, and returns a float.
    – Sammitch
    Apr 28, 2016 at 20:36

5 Answers 5

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
    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 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

-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???

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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