billynoah billynoah - 1 year ago 76
PHP Question

Determine if $x is divisible evenly by $y in PHP

I simply want to know if $x is evenly divisible by $y. For example's sake assume:

$x = 70;
$y = .1;

First thing I tried is:

$x % $y

This seems to work when both numbers are integers but fails if they are not and if
is a decimal less than 1 returns a "Division by zero" error, so then I tried:


Which returns equally confusing results, "0.099999999999996". states

Returns the floating point remainder of dividing the dividend (x) by the divisor (y)

Well according to my calculator
70 / .1 = 700
. Which means the remainder is 0. Can someone please explain what I'm doing wrong?

Answer Source

One solution would be doing a normal division and then comparing the value to the next integer. If the result is that integer or very near to that integer the result is evenly divisible:

$x = 70;
$y = .1;

$evenlyDivisable = abs(($x / $y) - round($x / $y, 0)) < 0.0001;

This subtracts both numbers and checks that the absolute difference is smaller than a certain rounding error. This is the usual way to compare floating point numbers, as depending on how you got a float the representation may vary:

php> 0.1 + 0.1 + 0.1 == 0.3
php> serialize(.3)
php> serialize(0.1 + 0.1 + 0.1)

See this demo:

php> $x = 10;
php> $y = .1;
php> abs(($x / $y) - round($x / $y, 0)) < 0.0001;
php> $y = .15;
php> abs(($x / $y) - round($x / $y, 0)) < 0.0001;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download