Dividing with a remainder in PHP

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;

$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.


The mathematical correct answer is:

remainder = dividend % divisor;
quotient = (dividend - remainder) / divisor;

and the remainder verifies the condition 0 <= remainder < abs(divisor).

Unfortunately, many programming languages (including PHP) don't handle the negative numbers correctly from the mathematical point of view. They use different rules to compute the value and the sign of the remainder. The code above does not produce the correct results in PHP.

If you need to work with negative numbers and get the mathematical correct results using PHP then you can use the following formulae:

$remainder = (($dividend % $divider) + abs($divider)) % abs($divider);
$quotient = ($dividend - $remainder) / $divider;

They rely on the way PHP computes modulus with negative operands and they may not provide the correct result if they are ported to a different language.

Here is a script that implements these formulae and checks the results against the values provided as example in the aforementioned mathematical correct answer.


A solution for positive and negative numbers:

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

Tags:

Php