PHP fmod() function
The fmod()
function in PHP calculates the floating-point remainder of the division of two numbers. It is similar to the modulus operator (%
), but while the modulus operator is generally used for integers, fmod()
is specifically designed for floating-point numbers.
Syntax:
- $dividend: The number to be divided.
- $divisor: The number by which to divide.
- Return Value: Returns the remainder of the division as a float. If the divisor is zero, it will result in a warning and return
NAN
.
Example 1: Basic Usage
Output:
Explanation: The division of 10.5
by 3.2
gives a quotient of 3
and a remainder of 1.9
.
Example 2: Negative Dividend
Output:
Explanation: When the dividend is negative, the result of fmod()
is also negative. Here, -10.5
divided by 3.2
gives a quotient of -4
and a remainder of -1.9
.
Example 3: Negative Divisor
Output:
Explanation: When the divisor is negative, fmod()
returns a result that is the same as if the divisor were positive. The output is still 1.9
.
Example 4: Both Negative
Output:
Explanation: When both the dividend and divisor are negative, the output remains negative. The output is -1.9
.
Example 5: Division by Zero
Output:
Explanation: Dividing by zero causes a warning, and the function returns NAN
(Not a Number).
Key Points:
- Floating-Point Precision:
fmod()
is particularly useful when dealing with floating-point numbers, as it maintains precision that can be lost with the%
operator in certain scenarios. - Behavior with Negatives: The sign of the result from
fmod()
follows the sign of the dividend, which is different from some other programming languages. - Usage: It can be used in scenarios where you need to find the remainder of floating-point divisions, such as in mathematical computations, simulations, or when working with percentages.
Example of Real-World Use:
Output:
Explanation: This example normalizes an angle to the range [0, 360)
by using fmod()
. The result of 370.0
degrees normalized to 10
degrees shows how fmod()
can be helpful in mathematical applications.
In summary, fmod()
is a powerful function in PHP for computing the floating-point remainder of a division operation, providing accuracy and flexibility when working with non-integer numbers.