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.?
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
*/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With