Using PHP fmod() Function to Compute Floating‑Point Remainder
The article explains PHP's fmod() function for calculating the remainder of two floating‑point numbers, describes its syntax and parameter roles, provides multiple code examples—including handling of zero divisors and negative values—and notes that it returns a float or NAN when appropriate.
In PHP, the fmod() function is used to calculate the remainder of two floating‑point numbers. Its syntax is: float fmod ( float $x , float $y ) The parameter $x is the dividend and $y is the divisor; the function returns the remainder of $x divided by $y as a floating‑point value.
The return type of fmod() is a float.
Note that fmod() works only with floating‑point numbers. For integer remainders, use the % operator.
Example 1:
$x = 10.5;
$y = 3.2;
$result = fmod($x, $y);
echo $result; // outputs 1.7This example shows that dividing 10.5 by 3.2 yields a remainder of 1.7.
Example 2:
$x = 7.2;
$y = 1.5;
$result = fmod($x, $y);
echo $result; // outputs 0.9Here, the remainder of 7.2 divided by 1.5 is 0.9.
When the divisor is zero, fmod() returns NAN (Not a Number).
Example 3 (divisor zero):
$x = 5.5;
$y = 0;
$result = fmod($x, $y);
echo $result; // outputs NANThis demonstrates the special handling of a zero divisor.
The function also has specific rules for negative numbers.
Example 4 (negative dividend):
$x = -5.5;
$y = 2.2;
$result = fmod($x, $y);
echo $result; // outputs -1.1In this case, the remainder of -5.5 divided by 2.2 is -1.1.
In summary, fmod() computes the floating‑point remainder of two numbers, returns a float, cannot be used for integer remainders, returns NAN when the divisor is zero, and follows particular rules for negative values.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
