Log in

View Full Version : Vertical Align using Printf



dgc223
06-12-2009, 05:24 PM
Hello,
I am a PHP newbie. I have some code that I built, for a restaurant receipt. I am trying to get the price data to be vertically aligned, using format rules (e.g., %9s, etc).
But I can't figure out how to get the format rule correct so that the numbers align vertically on the right side. Below is the code. Any suggestions would be greatly appreciated. Can't find this anywhere in the forums.

$hamburger = 4.95;
$milkshake = 1.95;
$cola = .85;
$food = 2 * $hamburger + $milkshake + $cola;
$tax = $food * .075;
$tip = $food * .16;
printf("%1d %9s at \$%.2f each: \$%.2f\n<br>", 2, 'Hamburger', $hamburger, 2 * $hamburger);
printf("%1d %9s at \$%.2f each: \$%.2f\n<br>", 1, 'Milkshake', $milkshake, $milkshake);
printf("%1d %9s at \$%.2f each: \$%.2f\n<br>", 1, 'Cola', $cola, $cola);
printf("%25s: \$%.2f\n <br>", 'Food and Drink Total', $food);
printf("%25s: \$%.2f\n <br>", 'Total with Tax', $food + $tax);
printf("%25s: \$%.2f\n <br>", 'Total with Tax and Tip', $food + $tax + $tip);

Here's how it looks now, as you can see price is not aligned vertical left..

2 Hamburger at $4.95 each: $9.90
1 Milkshake at $1.95 each: $1.95
1 Cola at $0.85 each: $0.85
Food and Drink Total: $12.70
Total with Tax: $13.65
Total with Tax and Tip: $15.68

Ideally it should be:

2 Hamburger at $4.95 each: $9.90
1 Milkshake at $1.95 each: $1.95
1 Cola at $0.85 each: $0.85
Food and Drink Total: $12.70
Total with Tax: $13.65
Total with Tax and Tip: $15.68

Jesdisciple
06-19-2009, 01:50 AM
Is there any specific reason to not use a table? I know the tableless movement is going through the web, but that's because folks use tables for things they weren't made for. This is exactly the kind of thing they were made for.

EDIT: Oh, and you're aligning the prices horizontally, not vertically.