Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 990
ha_ryu Avatar asked Oct 22 '25 19:10

ha_ryu


2 Answers

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 "    \tround\tfloor\tceil" . 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

*/
like image 62
Justinas Avatar answered Oct 25 '25 08:10

Justinas


floor() will always remove the values after the decimal, and only rounds down. round() will round up if the value after the integer provided is equal or higher than .5, else it will round down.

Example 1: round(1.5) returns 2 while floor(1.5) returns 1.

Example 2: Both round(3.2) and floor(3.2) return 3.

Example 3: round(2.9) returns 3 while floor(2.9) returns 2.

like image 36
UserName Name Avatar answered Oct 25 '25 09:10

UserName Name



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!