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:

fmod(float $dividend, float $divisor): float
  • $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

<?php echo fmod(10.5, 3.2); ?>

Output:

1.9

Explanation: The division of 10.5 by 3.2 gives a quotient of 3 and a remainder of 1.9.

Example 2: Negative Dividend

<?php echo fmod(-10.5, 3.2); ?>

Output:

-1.9

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

<?php echo fmod(10.5, -3.2); ?>

Output:

1.9

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

<?php echo fmod(-10.5, -3.2); ?>

Output:

-1.9

Explanation: When both the dividend and divisor are negative, the output remains negative. The output is -1.9.

Example 5: Division by Zero

<?php echo fmod(10.5, 0); ?>

Output:

Warning: Division by zero NAN

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:

<?php $angle = 370.0; $normalizedAngle = fmod($angle, 360.0); echo $normalizedAngle; // Normalize angle to the range [0, 360) ?>

Output:

10

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.