Reputation: 9267
Can someone explain why I am getting error Division by zero
when I want to use modulus operator and the second number is less than one (but more than 0 of course)
when I try
$a = 5
$b = 3
var_dump($a % $b);die; // result is as expected int(2)
but when I try this
$a = 5
$b = 0.5
var_dump($a % $b);die; // result is
Warning: Division by zero
bool(false)
PHP 5.4.4, debian 7
thanks
Upvotes: 4
Views: 2038
Reputation: 149020
The modulo operator discards the fractional part of it's operands. From the documentation:
Operands of modulus are converted to integers (by stripping the decimal part) before processing.
This can be observed with the following:
$a = 5;
$b = 3.6;
var_dump($a % $b);die; // int(2)
To avoid this behavior, use the fmod
method instead:
$a = 5;
$b = 0.5;
var_dump(fmod($a, $b));die; // float(0)
Upvotes: 10