Aligning printf() variables and decimals in C

后端 未结 2 558
北海茫月
北海茫月 2021-01-27 02:33

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

相关标签:
2条回答
  • 2021-01-27 02:50

    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.

    0 讨论(0)
  • 2021-01-27 02:53

    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().

    Sample code:

    #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;
    }
    

    Sample output:

    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
    
    0 讨论(0)
提交回复
热议问题