1

Hello I am trying to build a function to check if a number is multiple of another:

What I am trying to get:

my_function (10,2) = true
my_function (8,3) = false
my_function (9.5,0.5) = true
my_function (6,1.5) = true
my_function (1.1,0.1) = true

My function is:

//Check if $number1 is a multiple of $number2
function my_function( $number1, $number2 ){
    $_number = $number1 / $number2;  

    if( $_number == floor( $_number ) ) :
        return true;
    else :
        return false;
    endif;
}

It is working like a charm, except that for some reason when there are values 3,7,11, etc it is returning false when it should clearly return true:

my_function (5.4,0.3) = false (it is retruning false, it should be true!)
my_function (7.7,0.7) = false (it is retruning false, it should be true!)

Any idea why? Is it a compiler error? I run out of ideas. Thank you

u_mulder
  • 51,564
  • 5
  • 39
  • 54
karlosuccess
  • 691
  • 6
  • 19

1 Answers1

0

Since the resulting type of floor is double and $_number is also double, the safest way it to have a relative comparison < instead of absolute comparison.

Floating precision might vary. Thus, this is the safest way:

if (abs(floor( $_number ) - $_number) < 0.00001) {
    return true;
}

return false;
Joseph D.
  • 10,071
  • 3
  • 21
  • 54
  • 1
    This is dangerous and I beleive will still cause erorrs. What if the value of number is slightly below the desired number? i.e. `4/.5 = 7.999999999` this result will make it so it floors to 7, and then it will return false – Easton Bornemeier Jun 09 '17 at 22:26
  • 2
    @karlosuccess You may be interested in fmod later, check it out: http://php.net/manual/en/function.fmod.php – leoap Jun 09 '17 at 22:26
  • ok so if I use `fmod`, I still have to use `fmod( $number1, $number2 ) < 0.00001`, because even `fmod` also returns tiny decimals. So what is the answer then? – karlosuccess Jun 09 '17 at 22:50
  • @karlosuccess my area isn't math, so i can't help with the floating precision problem. I've asked some friends and they recommended me to check the BC Math extension, and linked me this: http://floating-point-gui.de/ and this: http://floating-point-gui.de/languages/php/ – leoap Jun 10 '17 at 01:50
  • @karlosuccess Yes, use `fmod( $number1, $number2 ) < 0.00001` – Easton Bornemeier Jun 10 '17 at 07:40