PHP Reference ยท Math Functions
PHP fmod() function
Reference for PHP fmod(): the floating-point remainder of a division, sign rules, how it differs from the % operator, division by zero and precision caveats.
fmod() returns the remainder of dividing one number by another, for floating-point numbers. It is the float version of the % operator. fmod(10.5, 3) is 1.5, because 3 * 3 = 9 and 10.5 - 9 = 1.5.
The % operator converts both operands to integers first, so 10.5 % 3 silently drops the fraction (and PHP 8.1 and later warns about the implicit conversion). Use fmod() whenever the numbers may have decimals, for example wrapping angles, finding the fractional part of a measurement or cycling through a repeating range.
<?php echo fmod(10.5, 3); // 1.5 echo fmod(370, 360); // 10
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
fmod(float $num1, float $num2): float
| Name | Description |
|---|---|
$num1 |
The dividend. |
$num2 |
The divisor. |
Return value: the remainder $num1 - n * $num2, where n is the quotient truncated toward zero. The result has the same sign as $num1 and its absolute value is smaller than that of $num2.
Special values: fmod(x, 0) returns NAN (it does not throw), fmod(INF, y) returns NAN, and fmod(x, INF) returns x for finite x.
Usage notes
- No exceptions. Unlike
%andintdiv(), which throwDivisionByZeroError,fmod()returnsNANfor a zero divisor. Check withis_nan()if the divisor can be zero. - Sign follows the dividend, as with
%. To get a always-positive "modulo" for negative numbers, add the divisor and take the remainder again, or use the pattern in the first example. - Floating-point noise. Decimals such as
0.1are stored approximately, sofmod(0.3, 0.1)is not0. Compare results with a tolerance, or scale to integers first (cents instead of dollars). - Integers: use
%when both values are integers; it is faster and exact. - Output type is always float, even for whole results:
fmod(9, 3)isfloat(0). - Named arguments:
fmod(num1: 7.5, num2: 2).
Related
intdiv(),ceil()andfloor(),round(),abs(), Arithmetic operators- Lessons: Math functions, Numbers