Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division by zero - php modulus with numbers less than one

Tags:

php

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

like image 859
dav Avatar asked Oct 28 '25 06:10

dav


1 Answers

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)
like image 199
p.s.w.g Avatar answered Oct 29 '25 21:10

p.s.w.g