Search code examples
cnumber-formatting

Format Adjustment in C


Like for example, I want to have this output

Subtotal           20
Discount(10%)    -  2   //negative sign always have 2 spaces out from '2'

I tried to code like this.

dis = subtotal*discount/100; //dis = 20*10/100
printf("Subtotal%13d\n",subtotal);
printf("Discount(%d%s)%4s-%3d\n",discount,"%"," ",dis);

But what if it has no discount, my output will become like this

Number are moved forward to left hand side

Subtotal           20
Discount(0%)    -  0

Also, if my subtotal and discount are very large.

Negative sign and number are sticking together

Subtotal         1000
Discount(50%)    -500

How to code this until my number never move forward to left hand side or right hand side in between the discount (0%-100%) and always make 2 spaces between negative sign and the numbers (dis) ?


Solution

  • You can do it, using:

    • the return of printf which tell you how characters have been printed
    • the log10 function which can be used to know the number of character in an integer:

    The code could looks like:

    #include <math.h>
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    /* get number of character in a number (when printed)*/
    int int_print_size(int number)
    {
        if (number < 1) 
            return 1;
    
        else 
            return 1+log10(number);
    }
    
    
    void print(int subtotal, int discount)
    {
        char spaces[] = "             ";
    
        int dis = subtotal*discount/100; //dis = 20*10/100
        int ref, len[2];
    
        /* take size of first line as reference */
        ref = printf("Subtotal%13d\n",subtotal);
        /* take the size of first part */
        len[0] = printf("Discount(%d%%)",discount);
        /* compute the printed size of `dis` */
        len[1] = int_print_size(dis);
    
        /* pad with characters from `spaces` array */
        printf("%.*s-  %d\n\n", ref-4-len[0]-len[1], spaces, dis);           
    
    } 
    
    int main(int argc, char *argv[]){       
        /* tests case */
        print(20, 0);
        print(20, 10);
        print(100, 9);
        print(100, 10);
        print(100, 11);
        print(1000, 50);
        print(100000, 99);
    
        return 0;
    }
    

    With result:

    Subtotal           20
    Discount(0%)     -  0
    
    Subtotal           20
    Discount(10%)    -  2
    
    Subtotal          100
    Discount(9%)     -  9
    
    Subtotal          100
    Discount(10%)   -  10
    
    Subtotal          100
    Discount(11%)   -  11
    
    Subtotal         1000
    Discount(50%)  -  500
    
    Subtotal       100000
    Discount(99%)-  99000