billynoah billynoah - 2 months ago 7
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
$y
is a decimal less than 1 returns a "Division by zero" error, so then I tried:

fmod($x,$y)


Which returns equally confusing results, "0.099999999999996".

php.net states
fmod()
:


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

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
bool(false)
php> serialize(.3)
'd:0.29999999999999999;'
php> serialize(0.1 + 0.1 + 0.1)
'd:0.30000000000000004;'

See this demo:

php> $x = 10;
int(10)
php> $y = .1;
double(0.1)
php> abs(($x / $y) - round($x / $y, 0)) < 0.0001;
bool(true)
php> $y = .15;
double(0.15)
php> abs(($x / $y) - round($x / $y, 0)) < 0.0001;
bool(false)