Alex Brooks
Alex Brooks

Reputation: 1151

Using printf to align doubles by decimal not working

I want to print doubles so that the decimals line up. For example:

1.2345
12.3456

should result in

 1.2345
12.3456

I have looked everywhere, and the top recommendation is to use the following method (the 5s can be anything):

printf(%5.5f\n");

I have tried this with the following (very) simple program:

#include <stdio.h>

int main() {
  printf("%10.10f\n", 0.523431);
  printf("%10.10f\n", 10.43454);
  return 0;
}

My output is:

0.5234310000
10.4345400000

Why doesn't this work?

Upvotes: 0

Views: 368

Answers (2)

mcleod_ideafix
mcleod_ideafix

Reputation: 11438

When you use "%10.10f" you are telling printf() "use 10 character positions to print the number (optional minus sign, integer part, decimal point and decimal part). From these 10 positions, reserve 10 for decimal part. If this is not possible, ignore the first number and use whatever positions needed to print the number so that the number of decimal positions is kept"

So that's what's printf() is doing.

So you need to indicate how many positions you are going to use, for example, 15, and how many positions from these are going to be decimals.... for example, 9. That will leave you with 5 positions for the minus sign and integer part and one position for the decimal point.

That is, try "%15.9f" in your printf's

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799230

The number before the . is minimum characters total, not just before the radix point.

printf("%21.10f\n", 0.523431);

Upvotes: 3

Related Questions