printf format float with padding

40,154

Solution 1

The following should line everything up correctly:

printf("ABC %6.1f DEF\n", test);
printf("ABC %6.1f DEF\n", test2);

When I run this, I get:

ABC 1234.5 DEF
ABC   14.5 DEF

The issue is that, in %5.1f, the 5 is the number of characters allocated for the entire number, and 1234.5 takes more than five characters. This results in misalignment with 14.5, which does fit in five characters.

Solution 2

You're trying to print something wider than 5 characters, so make your length specifier larger:

printf("ABC %6.1f DEF\n", test);
printf("ABC %6.1f DEF\n", test2);

The first value is not "digits before the point", but "total length".

Share:
40,154
nabulke
Author by

nabulke

Updated on September 23, 2020

Comments

  • nabulke
    nabulke over 3 years

    The following test code produces an undesired output, even though I used a width parameter:

    int main(int , char* [])
    {
        float test = 1234.5f;
        float test2 = 14.5f;
    
        printf("ABC %5.1f DEF\n", test);
        printf("ABC %5.1f DEF\n", test2);
    
        return 0;
    }
    

    Output

    ABC 1234.5 DEF   
    ABC  14.5 DEF
    

    How to achieve an output like this, which format string to use?

    ABC 1234.5 DEF   
    ABC   14.5 DEF
    
  • NPE
    NPE about 11 years
    @nabulke: Yes, every character counts.
  • phyatt
    phyatt over 5 years
    Note that if you have a chance of printing infinity or Nan, you may want to provide more space after the decimal (at least 4 characters). Then it becomes something like: printf("ABC %10.4f DEF\n", test);