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

This 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.9

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

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

This 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.1

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPmathfloating-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

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.