fmod() function in PHP

The fmod() function returns the floating-point remainder (modulo) of dividing two numbers. Unlike the modulo operator (%), fmod() handles floating-point numbers and returns a float result.

Syntax

fmod(dividend, divisor)

Parameters

  • dividend − The number to be divided.

  • divisor − The number that divides the dividend.

Return Value

The fmod() function returns the floating-point remainder of dividend/divisor. If the divisor is zero, it returns NAN (Not a Number).

Example

Here's a basic example demonstrating fmod() with integers ?

<?php
    $dividend = 30;
    $divisor = 9;
    $remainder = fmod($dividend, $divisor);
    echo "fmod(30, 9) = " . $remainder;
?>
fmod(30, 9) = 3

Working with Floating-Point Numbers

The main advantage of fmod() over the % operator is its ability to work with floating-point numbers ?

<?php
    $dividend = 20.5;
    $divisor = 3.2;
    $remainder = fmod($dividend, $divisor);
    echo "fmod(20.5, 3.2) = " . $remainder . "<br>";
    
    // Negative numbers
    $negative_remainder = fmod(-10.7, 3.0);
    echo "fmod(-10.7, 3.0) = " . $negative_remainder;
?>
fmod(20.5, 3.2) = 0.9
fmod(-10.7, 3.0) = -1.7

Comparison with Modulo Operator

Here's how fmod() differs from the % operator ?

<?php
    $a = 10.5;
    $b = 3;
    
    echo "Using fmod(): " . fmod($a, $b) . "<br>";
    echo "Using % operator: " . ($a % $b);
?>
Using fmod(): 1.5
Using % operator: 1.5

Conclusion

The fmod() function is essential for floating-point modulo operations in PHP. It provides precise remainder calculations for both integer and floating-point numbers, making it more versatile than the standard % operator.

Updated on: 2026-03-15T07:27:40+05:30

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements