PHP floor() function
The floor()
function in PHP rounds a number down to the nearest integer. This means it will take a floating-point number and return the largest integer that is less than or equal to that number.
Syntax:
- $number: The floating-point number you want to round down.
- Return Value: Returns the largest integer less than or equal to the input number, as a float.
Example 1: Rounding Down a Positive Decimal
Output:
Explanation: The number 4.7
is rounded down to the nearest integer, which is 4
.
Example 2: Rounding Down a Positive Decimal Close to the Next Integer
Output:
Explanation: 7.9
is rounded down to 7
, which is the largest integer less than 7.9
.
Example 3: Rounding Down a Negative Decimal
Output:
Explanation: For negative numbers, floor()
rounds down towards negative infinity. Therefore, -3.4
rounds down to -4
.
Example 4: Rounding Down an Integer
Output:
Explanation: If the input is already an integer (like 5
), the function returns the same integer without any changes.
Example 5: Rounding Down Zero
Output:
Explanation: The number 0
remains 0
because it is already the nearest integer.
Key Points:
- The
floor()
function always rounds down to the nearest integer. - It returns the result as a float, even though the value is an integer.
- It works with both positive and negative numbers.
- It is particularly useful in scenarios where you need to ensure that a number does not exceed a certain threshold, such as when calculating items per page in pagination or when determining the number of full units you can fit into a given quantity.
In summary, floor()
is a straightforward yet powerful function for rounding down numbers in PHP.