In languages like C or Python, if I divide an integer by an integer, I get an integer:
>>> 8/3 2
But in PHP, if I divide an integer by another integer with /
, sometimes I get a float:
php > var_dump(6/3); int(2) php > var_dump(8/3); float(2.6666666666667)
I'd like to do division like in Python or C, so that 8/3 is 2. How can I do that in PHP?
PHP | intdiv() Function. intdiv stands for integer division. This function returns the integer quotient of the division of the given dividend and divisor. This function internally removes the remainder from the dividend to make it evenly divisible by the divisor and returns the quotient after division.
In Python, the “//” operator works as a floor division for integer and float arguments. However, the division operator '/' returns always a float value. Note: The “//” operator is used to return the closest integer value which is less than or equal to a specified expression or value.
Solution: First, find the absolute values of the two integers. Next, divide the numbers or find their quotient. Finally, determine the final sign of the answer or quotient. Because we are dividing two integers with the same sign, the quotient will have a positive sign.
use round()
function to get integer rounded value.
round(8 / 3); // 3
or
Use floor()
function to get integer value
floor(8 / 3); // 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With