big problem with C today. So I want my variables to align in columns and be 2 decimal places at the same time.
I know to get to 2 decimal places I need to use %.2f and i
Try this:
printf("ItemA\t\t%30.2f @ $3.34 \t\t$ %30.2f\n", huhu, totalhuhu);
printf("ItemB\t\t%30.2f @ $44.50\t\t$ %30.2f\n", haha, totalhaha);
The \t are tabs to keep similar spacing. You can add as many as you want until you like it and %30.2f will give you a width of 30 before the decimal and a width of 2 after. This should give you your desired results for spacing.
Personally, I'd avoid tabs in the output. You can get the alignment to work if you're careful — primarily by using the same format string for each item. (Your choice of variable names makes that harder to fully automate; there are advantages to arrays of structures.)
If you want currency-sensitive formatting, look at the strfmon() function, and remember that a C program runs in the C locale until you set a different locale using setlocale().
#include <stdio.h>
#include <locale.h>
#include <monetary.h>
int main(void)
{
double huhu = 123.45;
double haha = 234.56;
double huhu_price = 3.34;
double haha_price = 44.50;
double totalhuhu = huhu * huhu_price;
double totalhaha = haha * haha_price;
char *huhu_name = "Item A";
char *haha_name = "Much Longer Name";
setlocale(LC_ALL, "");
const char fmt[] = "%-30s %10.2f @ $%6.2f $%20.2f\n";
printf(fmt, huhu_name, huhu, huhu_price, totalhuhu);
printf(fmt, haha_name, haha, haha_price, totalhaha);
char buffer1[32];
char buffer2[32];
const char p_fmt[] = "%-30s %10.2f @ %s %s\n";
const char price[] = "%(7.2n";
const char cost[] = "%(21.2n";
strfmon(buffer1, sizeof(buffer1), price, huhu_price);
strfmon(buffer2, sizeof(buffer2), cost, totalhuhu);
printf(p_fmt, huhu_name, huhu, buffer1, buffer2);
strfmon(buffer1, sizeof(buffer1), price, haha_price);
strfmon(buffer2, sizeof(buffer2), cost, totalhaha);
printf(p_fmt, haha_name, haha, buffer1, buffer2);
return 0;
}
Item A 123.45 @ $ 3.34 $ 412.32
Much Longer Name 234.56 @ $ 44.50 $ 10437.92
Item A 123.45 @ $3.34 $412.32
Much Longer Name 234.56 @ $44.50 $10,437.92