o6t9o o6t9o - 5 months ago 12
Java Question

Lining up decimal points using System.out.printf

I am trying to line up my output so my decimal points line up correctly. I am very close to achieving this, but the hundreds place does not line up correctly. Any help would be appreciated.

After day 1 you have $ 0.02
After day 2 you have $ 0.04
After day 3 you have $ 0.08
After day 4 you have $ 0.16
After day 5 you have $ 0.32
After day 6 you have $ 0.64
After day 7 you have $ 1.28
After day 8 you have $ 2.56
After day 9 you have $ 5.12
After day 10 you have $ 10.24
After day 11 you have $ 20.48
After day 12 you have $ 40.96
After day 13 you have $ 81.92
After day 14 you have $ 163.84
After day 15 you have $ 327.68
After day 16 you have $ 655.36
After day 17 you have $ 1,310.72
After day 18 you have $ 2,621.44
After day 19 you have $ 5,242.88
After day 20 you have $ 10,485.76
After day 21 you have $ 20,971.52
After day 22 you have $ 41,943.04
After day 23 you have $ 83,886.08
After day 24 you have $ 167,772.16
After day 25 you have $ 335,544.32
After day 26 you have $ 671,088.64
After day 27 you have $ 1,342,177.28
After day 28 you have $ 2,684,354.56
After day 29 you have $ 5,368,709.12
After day 30 you have $10,737,418.24


My code is System.out.printf("After day %d you have $%,13.2f\n", day, money);

Answer

Try this:

System.out.printf("After day %2d you have $%,13.2f\n", day, money);

%2d will right indent the number, and will take 2 charater space.

Comments