tags:

views:

759

answers:

4

I have a part in my code where I need to divide and have a remainder instead of a decimal answer.

How can I do this?

thanks

+3  A: 

You can do what you are describing using the "%" (modulus) operator. The following code is an example of dividing with a remainder.

$remainder=$num % $divideby;
$number=explode('.',($num / $divideby));
$answer=$number[0];
echo $answer.' remainder '.$remainder;
Sam152
Don’t use a string function on a float type. Better use `floor()`.
Gumbo
blindly using floor could fail on a negative result
Paul Dixon
+4  A: 
$quotient = intval($dividend / $divisor);
$remainder = $dividend % $divisor;

Using intval instead of floor will round the quotient towards zero, providing accurate results when the dividend is negative.

Alex Barrett
can yield wrong result if negative, e.g. if dividend=5 and divisor=2 you'd calculate 3 as the quotient rather than 2
Paul Dixon
Yes, I noticed that soon after posting and revised my reply to use `intval` rather than `floor`.
Alex Barrett
+1  A: 

A solution for positive and negative numbers:

$quotient = $dividend / $divison;
$integer = (int) ($quotient < 0 ? ceil($quotient) : floor($quotient));
$remainder = $dividend % $divisor;
Gumbo
+1  A: 

If you need to look it up, the % operator is called mod (or modulus).

adam