Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf format float with padding

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 
like image 824
nabulke Avatar asked Mar 07 '13 09:03

nabulke


People also ask

How do I add padding to printf?

If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following. char *ptr = "Hello"; printf("%40s\n", ptr); That will give you 35 spaces, then the word "Hello".

What does %% mean in printf?

As % has special meaning in printf type functions, to print the literal %, you type %% to prevent it from being interpreted as starting a conversion fmt.

What is %d %f %s in C?

%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].

What is %g in C?

%g. It is used to print the decimal floating-point values, and it uses the fixed precision, i.e., the value after the decimal in input would be exactly the same as the value in the output.


1 Answers

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.

like image 103
NPE Avatar answered Sep 22 '22 20:09

NPE