3

I read here that:

Modulus with non integer numbers will give unpredictable results.

However, I tried to play a bit with it, and it seems to give pretty predictable results:

function mod($a, $b) {
    echo "$a % $b = " . ($a % $b) . '<br>';
}
mod(10.3, 4);
mod(10.3, 2);
mod(-5.1, 3);

// OUTPUT:
//   10.3 % 4 = 2
//   10.3 % 2 = 0
//   -5.1 % 3 = -2

In other words, the double seems to be converted to integer first.

Is there any definition of how % works when the first operand is double?

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

1 Answers1

5

use:

fmod(10.3, 4)

I too had to do the same thing but I noticed doubles are converted to int and using fmod returns a double.

If this helps

From http://php.net/manual/en/language.operators.arithmetic.php

The result of the modulus operator % has the same sign as the dividend — that is, the result of $a % $b will have the same sign as $a.

Class
  • 3,149
  • 3
  • 22
  • 31
  • 1
    Thanks for your answer. Note that I'm not interested in the `double` remainder (i.e. what `fmod` returns), but rather in understanding of how `%` works when the first operand is `double`. – Misha Moroshko Jan 15 '13 at 02:51
  • @MishaMoroshko I edited my answer if it helps on what you were looking for. – Class Jan 15 '13 at 03:17
  • Thanks for trying, but unfortunately your answer doesn't really address the question. – Misha Moroshko Jan 15 '13 at 03:56