Backend Development 4 min read

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.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP fmod() Function to Compute Floating‑Point Remainder

In PHP, the fmod() function is used to calculate the remainder of two floating‑point numbers. Its syntax is:

<code>float fmod ( float $x , float $y )</code>

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:

<code>$x = 10.5;
$y = 3.2;
$result = fmod($x, $y);
echo $result; // outputs 1.7</code>

This example shows that dividing 10.5 by 3.2 yields a remainder of 1.7.

Example 2:

<code>$x = 7.2;
$y = 1.5;
$result = fmod($x, $y);
echo $result; // outputs 0.9</code>

Here, 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):

<code>$x = 5.5;
$y = 0;
$result = fmod($x, $y);
echo $result; // outputs NAN</code>

This demonstrates the special handling of a zero divisor.

The function also has specific rules for negative numbers.

Example 4 (negative dividend):

<code>$x = -5.5;
$y = 2.2;
$result = fmod($x, $y);
echo $result; // outputs -1.1</code>

In 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.

backendPHPmathFloating Pointremainderfmod
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.