Home > Mobile >  How can I align a certain digit in a list with printf?
How can I align a certain digit in a list with printf?

Time:09-29

I'm trying to format my printf statement(s) so that the ones digits of all the outputs are aligned, for example

Sum:                        45
Average:                    22.50
Difference:                  5
Product:                   500
Distance:                    5
Maximum:                    25
Minimum:                    20

I am using

System.out.printf("%.30s0d%n", "Sum:", getSum());
System.out.printf("%.30s0f%n", "Average:", getAverage());

but that yields the result in a weird way:

Sum:                           233
Average:                      0.002155

Anyone know what I'm doing wrong? Thanks in advance.

CodePudding user response:

Maybe this could help:

System.out.printf("%.30s0f%n", "Sum:", (double)getSum());
System.out.printf("%.30s0f%n", "Average:", getAverage());

Output

Sum:                    233.000000
Average:                  0.002155

CodePudding user response:

Here are two possibilities. Pick the one that you like.

System.out.printf("%-10sd%n", "Sum:", 100);
System.out.printf("%-10s.2f%n", "Average:", 3.5);

System.out.printf("s:d%n", "Sum", 100);
System.out.printf("s:.2f%n", "Average", 3.5);
  • Related