note 126829 added to function.intdiv
| From: | oittaa at main dot php dot net | Date: | Sun, 06 Feb 2022 04:56:44 +0000 |
| Subject: | note 126829 added to function.intdiv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-217583@lists.php.net to get a copy of this message | ||
Python style integer division, where the result is always rounded towards minus infinity.
1 // 2 is 0
(-1) // 2 is -1
1 // (-2) is -1
(-1) // (-2) is 0
<?php
function intdiv_py(int $num1, int $num2): int{
if ($num1 < 0 xor $num2 < 0){
$num1 = abs($num1);
$num2 = abs($num2);
$remainder = $num1 % $num2;
return $remainder ? -1 -($num1 - $remainder) / $num2 : -$num1 / $num2;
}
return intdiv($num1, $num2);
}
var_dump(intdiv_py(1, 2)); // 0
var_dump(intdiv_py(-1, 2)); // -1
var_dump(intdiv_py(1, -2)); // -1
var_dump(intdiv_py(-1, -2)); // 0
?>
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.135 (proxied: 81.202.57.120)
----
Manual Page -- https://php.net/manual/en/function.intdiv.php
Edit -- https://main.php.net/note/edit/126829
Del: integrated -- https://main.php.net/note/delete/126829/integrated
Del: useless -- https://main.php.net/note/delete/126829/useless
Del: bad code -- https://main.php.net/note/delete/126829/bad+code
Del: spam -- https://main.php.net/note/delete/126829/spam
Del: non-english -- https://main.php.net/note/delete/126829/non-english
Del: in docs -- https://main.php.net/note/delete/126829/in+docs
Del: other reasons-- https://main.php.net/note/delete/126829
Reject -- https://main.php.net/note/reject/126829
Search -- https://main.php.net/manage/user-notes.php