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
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
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.
A solution for positive and negative numbers:
$quotient = $dividend / $divison;
$integer = (int) ($quotient < 0 ? ceil($quotient) : floor($quotient));
$remainder = $dividend % $divisor;
If you need to look it up, the % operator is called mod (or modulus).