Bernardo Araujo Bernardo Araujo - 1 year ago 52
Java Question

Usage of String.format in Java

What I wanted to print:

Coca-Cola $ 11.00
Pepsi $ 9.45
Sprite $ 8.50

What end up printing:

Coca-Cola $ 11
Pepsi $ 9.45
Sprite $ 8.5

My code:

public void test(){
for (int i = 0; i<20; i++){
System.out.println(String.format("%20s%n", "$ "+price[i]));;


I am looking for this for like 2 hours, perhaps I'm not that good specifying my search terms, but I'll try to avoid some more hours of searching and suffering by simply asking... Sorry for not knowing enough to properly find this on the forums or specify my title and thank you very much.

Answer Source

The problem of your code is that it first prints the product then it try to print a formatted string.

The battle is already lost when it print those things separately. Because the second print needs to know the length of the product to determine how many spaces it needs to align the prices. That number is definitely not going to be the same.

Try this instead:

System.out.printf("%-20s$ %5.2f\n", product[i], price[i]);


Coca-Cola           $ 11.00
Pepsi               $  9.45
Sprite              $  8.50

The %-20s will left justify the product name, fill required number of spaces after the product name.

To align the decimal point, we need to specify the total length of the formatted number as well. With %5.2, we ask for a total length of 5, which 11.00 fits well, you can tune up this number if price is greater than 99.

Good luck.