Mastering PHP’s fmod(): Calculate Float Remainders with Examples
This article explains how PHP's fmod() function computes the remainder of two floating‑point numbers, outlines its syntax, highlights important usage notes such as handling zero divisors and negative values, and provides four clear code examples demonstrating typical scenarios.
fmod() function usage
In PHP, fmod() calculates the remainder of two floating‑point numbers. Syntax: float fmod ( float $x , float $y ). $x is the dividend, $y the divisor, and the function returns a float.
Note that fmod() works only with floats; use the % operator for integer remainders.
Example 1
$x = 10.5;
$y = 3.2;
$result = fmod($x, $y);
echo $result; // 1.7This calculates 10.5 ÷ 3.2 remainder, outputting 1.7.
Example 2
$x = 7.2;
$y = 1.5;
$result = fmod($x, $y);
echo $result; // 0.9Result is 0.9.
Example 3
$x = 5.5;
$y = 0;
$result = fmod($x, $y);
echo $result; // NANIf the divisor is zero, fmod() returns NAN.
Example 4
$x = -5.5;
$y = 2.2;
$result = fmod($x, $y);
echo $result; // -1.1Negative numbers follow specific rules; this example yields -1.1.
Summary
The fmod() function computes the floating‑point remainder of $x divided by $y, returning a float. It cannot be used for integer remainders, returns NAN when $y is zero, and has defined behavior for negative operands.
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.
