Tabular format / print spacing in Java

So this piece of code has been listening to me for the last hour or so. Basically, part of my programming task is to display data in a tabular format. It remains only to make the result look beautiful, so to speak.

Here is a (example) segment of code that was listening to me in terms of the formatting / syntax of the printf command:

System.out.printf("%-20s %-20s %-20s %-20s %-20s%n",
                "Part #:", "Description:", "Number Sold:", "Price:", "Total:");
System.out.println
        ("---------------------------------------------------------------------------------------------------------------");
System.out.printf("%-20s %-20s %-20d %s%-20.2f %s%-20.2f%n",
                "2304E", "Power Drill", 20, "$",99.99, "$",100*99.99);

      

Thing is when I try to run a command on NetBeans I seem to get this in my output:

enter image description here

While it's not exactly the right thing to do for programming or a big deal, that little little numbered indentation at the bottom right of the header is Total:

bugging me.


I've tried for the past hour or so to get the "$ 9999.00" double / float value fully aligned in the "Total:" header. Any help would be appreciated.

tl; dr - Look at the image link, then look at the code. Trying to get the number to the right below "Total" is pressed to the left. Help?

+3


source to share


1 answer


Additionally $

, placed in %s

, another character is added to your column which makes it wider than expected by 20 characters. Because of this, the characters in the following columns are shifted to the right. If you want the columns price

and total

always contain 20 characters, you can

  • decrease each %-20.2f

    to %-19.2f

    (if %s

    will only contain one character),
  • generate string "$99,99"

    like first String.format("$%.2f",99.99)

    and use it as argument for %-20s

    (which will replace %s%-20.2f

    ).

So your code might look like



System.out.printf("%-20s %-20s %-20d %s%-19.2f %s%-19.2f%n",
        "2304E", "Power Drill", 20, "$",99.99, "$",100*99.99);

      

or

System.out.printf("%-20s %-20s %-20d %-20s %-20s%n",
        "2304E", "Power Drill", 20, String.format("$%.2f",99.99), String.format("$%.2f",100*99.99));

      

0


source







All Articles