Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pad a printf to take account of negative signs and variable length numbers?

I'm trying to output some numbers in a log file and I want to pad a load of floats via the printf function to produce:

 058.0  020.0  038.0 -050.0  800.0  150.0  100.0 

Currently I'm doing this:

printf("% 03.1f\n", myVar); 

...where myVar is a float. The output from that statement looks like this:

58.0 20.0 38.0 -50.0 800.0 150.0 100.0 

From what I've read I would expect my code to produce the output I mentioned at the top of this post, but clearly something is wrong. Can you only use one flag at a time? ..or is there something else going on here?

like image 379
Jon Cage Avatar asked Mar 16 '11 12:03

Jon Cage


People also ask

What is the purpose of the flag -( hyphen in printf () function?

The # is a flag that modifies the output of the format specifier (which you don't provide in your string).

What is %A in printf?

The %a formatting specifier is new in C99. It prints the floating-point number in hexadecimal form. This is not something you would use to present numbers to users, but it's very handy for under-the-hood/technical use cases. As an example, this code: printf("pi=%a\n", 3.14); prints: pi=0x1.91eb86p+1.

How do I left justify using printf?

printf allows formatting with width specifiers. For example, printf( "%-30s %s\n", "Starting initialization...", "Ok." ); You would use a negative width specifier to indicate left-justification because the default is to use right-justification.

Can we use printf () apart from just printing values if yes then where?

The printf function of C can do a lot more than just printing the values of variables. We can also format our printing with the printf function. We will first see some of the format specifiers and special characters and then start the examples of formatted printing.


1 Answers

The width specifier is the complete width:

printf("%05.1f\n", myVar);  // Total width 5, pad with 0, one digit after . 

To get your expected format:

printf("% 06.1f\n", myVar); 
like image 127
Erik Avatar answered Oct 13 '22 10:10

Erik