0

I've been looking through the forum to find an exact answer to this, but have been unable to do so. Here is my code:

String item = String.format("%-6s $%-6.2f Number in Inventory: %-3d", this.getBarcode(), this.getPrice(), this.getInventory());

The output looks like this for two items put in:

DR4423 $700.04 Number in Inventory: 24 
LD342  $1234.24 Number in Inventory: 425

The output should look like this, with an extra character space in the price for Number in Inventory to line up:

DR4423 $ 700.04 Number in Inventory: 24 
LD342  $1234.24 Number in Inventory: 425

How do I make the "Number in Inventory" line up? It looks like the first item in the example lost an empty character space as it only has 5 digits instead of 6 for the price. Thanks in advance for the help.

1
  • I need there to be exactly 6 character spaces for the price. Edits to the question to show expected output. Commented Dec 5, 2015 at 23:49

3 Answers 3

4

I think you need to use:

String.format("%-6s $%-7.2f Number in Inventory: %-3d", this.getBarcode(), this.getPrice(), this.getInventory());

Or, if you want the space added to the front:

String.format("%-6s $%#7.2f Number in Inventory: %-3d", this.getBarcode(), this.getPrice(), this.getInventory());

Notice the %-7 instead of %-6. The period is counted as a character.

Sign up to request clarification or add additional context in comments.

3 Comments

That worked similar to the \t, without extra spaces from the tab. Great answer, but I am looking for a space after the $ sign.
@javanewb2.0 Try using a hash # instead of dash -. :)
The hash # did exactly what I needed. Thank you!
1

- in %-6.2f means you want passed number to be aligned to left, like:

|123,45|
|123,40|
|123,00|
|12,00 |
|1,00  |

If you want to align your number to right like:

|123,45|
|123,40|
|123,00|
| 12,00|
|  1,00|

then simply remove this -.

You should should also probably set minimal used length to 7 since . also takes some space which means that to produce

| 700.04|
 1234567

you need 7 characters.

So try with %-6s $%7.2f Number in Inventory: %-3d

Comments

0

Inserting a \t between the price and 'Number' should work just fine in your case.

1 Comment

That worked for how my expected output did read, but I missed a space. I updated it to put a space between the $ and the price when the price does not have 6 digits. This is how I am looking to format it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.