35

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?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Jon Cage
  • 36,366
  • 38
  • 137
  • 215

2 Answers2

32

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);
Erik
  • 88,732
  • 13
  • 198
  • 189
  • 1
    Yep, that's it. I hadn't realised the padding included the decimal point etc. ...although it needs to be 06 to include the space or sign value. – Jon Cage Mar 16 '11 at 12:24
1

follows Erik, but I find

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

also works.

lumw
  • 297
  • 1
  • 9