Parse comma separated lines, calculate a total for each and for all, and print money in a clean format.
What to build
A program that prints the total of every line and the grand total.
Requirements
- Read n, then n lines in the form
name,quantity,pricewhere the price is a whole number of cents. - For every line print
name: D.CCwith the line total (quantity times price) in dollars and cents. - Then print
TOTAL: D.CCfor all lines together.
Input
Line 1: n. Then n lines name,quantity,price.
Output
n + 1 lines.
Constraints
1 ≤ n ≤ 30; names have no commas; every total is below 1000000 cents.
Example
Input:
2
pen,3,150
book,2,1299
Output:
pen: 4.50
book: 25.98
TOTAL: 30.48
Why it works
Keeping money in whole cents avoids float errors, and intdiv with % splits it into dollars and cents only when printing.
Examples
Example 1 · Input
2 pen,3,150 book,2,1299
Expected output
pen: 4.50 book: 25.98 TOTAL: 30.48
Example 2 · Input
1 tea,1,5
Expected output
tea: 0.05 TOTAL: 0.05
Hints
Hint 1
explode(",", $line) splits a line into name, quantity and price in cents.
Hint 2
Format cents with sprintf("%d.%02d", intdiv($c, 100), $c % 100).
Solution
Show one correct solution (try it yourself first)
<?php
function money(int $cents): string
{
return sprintf("%d.%02d", intdiv($cents, 100), $cents % 100);
}
$n = (int) trim(fgets(STDIN));
$totals = [];
for ($i = 0; $i < $n; $i++) {
[$name, $qty, $price] = explode(",", trim(fgets(STDIN)));
$total = (int) $qty * (int) $price;
$totals[] = $total;
echo $name, ": ", money($total), "\n";
}
echo "TOTAL: ", money(array_sum($totals)), "\n";