fmod() in PHP is the worst !”#¤%&/()= function ever!

I hate floating point artithmetic and I really hate fmod() in PHP. It’s useless.

fmodReturns the floating point remainder (modulo) of the division of the arguments

If you calculate 36 modulo 7.2?  What do you get? Zero, yes. 7.2*5=36. No remainder!

What if you use fmod in PHP?

$ php -r 'echo fmod(36,7.2);'
7.2

WTF? Excuse me? Is that the result from IEEE 754 hell, a parallel universe, or what?

Now I’m betting on the function below. I hope it won’t let me down.

function modulo($n,$b) {
return $n-$b*floor($n/$b);
}


2 comments

  1. Could it be possible that ‘echo’ is truncating the value? E.g. printing 7.199999999999 as 7.2.

    Then you have the problem of exact representability of course. Did you try this in C/C#/Java?

  2. @Carl

    Indeed:

    $ php -d precision=40 -r ‘echo fmod(36,7.2);’
    7.199999999999999289457264239899814128876

    So, fmod() actually thinks that 36 is 4*7.2 + the above?

Leave a Reply to Carl Ådahl Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.