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';
basagabi
  • 4,900
  • 6
  • 38
  • 84
  • 1
    NOT the same results: `var_dump( intval($num) ); var_dump( floor($num) );` also check `var_dump( intval(-$num) ); var_dump( floor(-$num) );` – AbraCadaver Apr 28 '16 at 20:19
  • 1
    `intval()` discards the decimal portion, and returns an integer. `floor()` rounds down, and returns a float. – Sammitch Apr 28 '16 at 20:36

5 Answers5

21

The functions give different results with negative fractions.

echo floor(-0.1); // -1
echo intval(-0.1); // 0
nl-x
  • 11,762
  • 7
  • 33
  • 61
  • 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 '16 at 20:27
  • 1
    @basagabi floor() doesn't round it. It returns the nearest integer which is less than the given value – Ahmed Shefeer Jun 19 '20 at 15:29
6

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

axiac
  • 68,258
  • 9
  • 99
  • 134
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.

WillardSolutions
  • 2,316
  • 4
  • 28
  • 38
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

Sammitch
  • 30,782
  • 7
  • 50
  • 77
-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???

Siddharth Thevaril
  • 3,722
  • 3
  • 35
  • 71