Skip to content
Advertisement

What is the Difference between Floor and Round

         CODE                            RESULTS

$a = floor(3.5);                         //3
$b = round(3.5, 0, PHP_ROUND_HALF_DOWN); //3
var_dump($a);                            //float(3)
var_dump($b);                            //float(3)
$c = gettype($a);                        //double
$d = gettype($b);                        //double

What are the difference.? when do I use floor() or round() for the number above.?

Advertisement

Answer

floor() will simply drop decimal value and return only integer.

So floor(1.2) => 1 and floor(1.9) => 1.

Meanwhile round() will round number that has decimal value lower than 0.5 to lower int, and when more than 0.5 to higher int:

So round(1.2) => 1 but round(1.9) => 2

Also round() has more options, like precision and rounding options.


Example:

$nums = [-1.5, -1, -.8, -.4, 0, .4, .8, 1, 1.5];

echo "    troundtfloortceil" . PHP_EOL;
foreach ($nums as $a) {
    echo $a . ": t" . round($a) . "t" . floor($a) . "t" . ceil($a) . PHP_EOL;
}

/*
        round   floor   ceil
-1.5:   -2      -2      -1
  -1:   -1      -1      -1
-0.8:   -1      -1      -0
-0.4:   -0      -1      -0
   0:    0       0       0
 0.4:    0       0       1
 0.8:    1       0       1
   1:    1       1       1
 1.5:    2       1       2

*/
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement