So this snippet of code has been bugging me for the past hour or so. Basically, part of my program's task is to display data in a sort of tabular format. Only thing left is to just make the output look nice, so to speak.
Here is the (example) segment of code that's been bugging me in terms of 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, once I try to run the command on NetBeans, I seem to be getting this on my output:
While this isn't exactly program-breaking or a big deal, that small little indent on the number right bellow the Total:
header is bugging me.
I've been trying for the past hour or so to get the "$9999.00" double/float value perfectly aligned bellow the "Total:" header. Any assistance would be appreciated.
tl;dr - Look at Image Link, then look at code. Trying to get the number right bellow "Total" pushed to the left. Help?
Extra $
placed in %s
is adding another character to your column which makes it wider than expected 20 characters. Because of that characters in next columns are shifted to the right. If you want price
and total
columns to always contain 20 characters you can
%-20.2f
to %-19.2f
(assuming %s
will hold only one character), "$99,99"
string first like String.format("$%.2f",99.99)
and use it as argument for %-20s
(which will replace %s%-20.2f
).So your code can 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));