[英]Java Format String Spacing
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. 看起来示例中的第一项丢失了一个空字符空间,因为它只有5位数字而不是价格的6位数字。 Thanks in advance for the help. 先谢谢您的帮助。
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
. 注意%-7
而不是%-6
。 The period is counted as a character. 句点被视为字符。
在价格和“数字”之间插入\\t
应该可以正常工作。
-
in %-6.2f
means you want passed number to be aligned to left, like: -
在%-6.2f
表示您希望传递的数字向左对齐,例如:
|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 .
从开始,您还应该将最小已用长度设置为7
.
also takes some space which means that to produce 也需要一些空间
| 700.04|
1234567
you need 7 characters. 您需要7个字符。
So try with %-6s $%7.2f Number in Inventory: %-3d
因此,请尝试使用%-6s $%7.2f Number in Inventory: %-3d
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.