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!


Posted on Wednesday 15 December 2010 to the category Blog |
Used tags: , , , ,

Share to your favourite website

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Del.icio.us
  • Digg
  • Google
  • Reddit
  • StumbleUpon
  • Facebook
  • Twitter

Comments

Nice site . :)
CycleTiessy - Wednesday 15 December 2010 at 11:40am

One or more comments are waiting for approval by an editor.

Leave a comment