Floats module in PHP returns integers?

12

How do I get the rest of the division (modulo % operation) to decimal places when I use a divisor or float dividend?

Example:

echo 5 % 3; // imprime 2 como é esperado
echo 5.6 % 3; // imprime 2 quando deveria imprimir 2.6
    
asked by anonymous 20.12.2013 / 13:20

3 answers

17

You can use fmod that is appropriate for this. I do not know if it will give the result you expect, but in my quick test it was ok.

Then you would:

echo fmod( 5.6, 3.0 );

This will print 2.6 . See working on ideone and in PHP Sandbox a>. And I put it in Github for future reference .

    
20.12.2013 / 13:27
7

The Module operator, server only for integers, for such use, you can use the fmod of PHP:

fmod(5.6, 3); // imprime 2.6

If you use only the Module operator (%), the value obtained will be the largest integer smaller than the result.

    
20.12.2013 / 13:27
4

This operator works only with integers

You have a comment on this link .

  

Note that the% (modulo) operator works only with integers (between -214748348 and 2147483647) ...

Try using fmod()

    
20.12.2013 / 13:24