How to: calculate the modulus (mod or %) of a float in PHP
This little caveat totally stumped me for at least an hour. I was trying to calculate the modulus of a floating point number in PHP.
For those who do not know what the modulus (or mod for short) operator is, it calculates the remainder after doing division. In PHP we use the % operator to calculate modulus.
For an example, try doing this in PHP:
<?php echo 4.5 % 3; ?>
In this case we would expect 3 to go into 4.5 once, with a remainder of 1.5. PHP automagically converts the values of a modulus operation to integers, so it was calculating 4 mod 3, which equals 1.
To work out the modulus of a floating point number, simply use the included PHP function fmod($x, $y)
<?php echo fmod(4.5, 3); ?>
This successfully produces 1.5 - problem solved!
Share to your favourite website
Comments
One or more comments are waiting for approval by an editor.