Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP modulus operator for doubles

Tags:

php

double

modulo

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?

like image 397
Misha Moroshko Avatar asked Mar 13 '26 17:03

Misha Moroshko


1 Answers

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.

like image 140
Class Avatar answered Mar 16 '26 07:03

Class