The floor() function in PHP is used to round a floating-point number down to the nearest whole integer (toward negative infinity).
Syntax:
float floor ( float $value )
- $value: The input number you want to round down.
How it Works:
- It takes a number and returns the largest integer less than or equal to that number.
Example 1: Basic Usage
<?php
echo floor(4.7); // Outputs: 4
echo floor(4.3); // Outputs: 4
?>
Explanation:
4.7 and 4.3 both get rounded down to 4.
Example 2: Negative Numbers
<?php
echo floor(-4.3); // Outputs: -5
echo floor(-4.7); // Outputs: -5
?>
Explanation:
- With negative numbers,
floor() moves "down" the number line, so -4.3 goes to -5 (more negative).
Example 3: Using with Calculations
<?php
$price = 9.99;
$discount = 0.15;
$finalPrice = floor($price - ($price * $discount));
echo $finalPrice; // Outputs: 8
?>
Explanation:
- After applying the discount, the price is
8.4915. floor() rounds it down to 8.
When to Use:
- When you need to ensure values are rounded down for things like:
- Pagination calculations.
- Pricing where you can't exceed a certain threshold.
- Trimming decimal points without rounding up.