PHP — Variables, integers, and intdiv
PHP intdiv returns an integer quotient. For a nonnegative price in cents, dividing by 100 gives the dollar amount and the remainder gives the cents.
A simple example
Change a stored number
- Start with n starts at 2
- Do this Add 1 to n
- Result 3
<?php
$n = 2;
$n += 1;
echo $n, PHP_EOL;
3
Calculate a receipt in cents
PHP variable names start with a dollar sign. intdiv returns a whole-number quotient. The percent operator produces the remaining cents, and printf pads them to two digits.
A student buys three notebooks at 125 cents each. Add the 50-cent delivery charge once for the whole order. Keeping the arithmetic in cents makes the total easy to check against the receipt.
Run the example
PHP 8 or later. Run these commands from the directory containing the example.
php lesson.php
<?php
declare(strict_types=1);
$priceCents = 125;
$quantity = 3;
$total = $priceCents * $quantity + 50;
printf("%d.%02d\n", intdiv($total, 100), $total % 100);
4.25
Three items at 125 cents cost 375 cents. Adding one 50-cent delivery charge gives 425 cents. The quotient and remainder on division by 100 give 4 dollars and 25 cents.
Try it yourself
What happens if each item costs 101 cents?
Check your answer
Three items plus delivery cost 353 cents, so the output becomes 3.53.