Java:如何正确证明$?
以下是我得到的:
outputStr = name + "\n" + "Gross Amount:$ " + String.format("%.2f", grossAmount) + "\n"
+ "Federal Tax:$ " + String.format("%.2f", fedIncomeTax) + "\n" + "State Tax:$ "
+ String.format("%.2f", stateTax) + "\n" + "Social Security Tax:$ " + String.format("%.2f", ssTax)
+ "\n" + "Medicare/Medicaid Tax:$ " + String.format("%.2f", medicareTax) + "\n" + "Pension Plan:$ "
+ String.format("%.2f", pensionPlan) + "\n" + "Health Insurance:$ " + String.format("%.2f", HEALTH_INSURANCE)
+ "\n" + "Net Pay:$ " + String.format("%.2f", netPay);
System.out.println(outputStr);
它是这样打印出来的:
Random Name
Gross Amount:$ 3575.00
Federal Tax:$ 536.25
等等
但我想右对齐$15和15个空格,这是怎么做到的?我想要这样:
Gross Amount: $3575.00
提前谢谢
# 1 楼答案
Printf在这里是一个很好的实现,但是字符串格式应该适合您的需要
字符串格式背后的想法是,你正在构建一个字符串,然后通过字符串的参数向其中添加字符。格式化和打印。希望这有帮助