Java - toString格式化(格式化双打)

时间:2015-07-21 20:48:45

标签: java formatting tostring

我正在处理的项目要求使用toString方法打印银行帐户余额。我不允许向我当前的程序添加任何方法,但我需要将myBalance变量格式化为一个双精度数,而不是一个小数位。在这个特殊情况下,我的程序应该打印8.03,但它打印8.0。

这是我的toString方法:

   public String toString()
   {
      return"SavingsAccount[owner: " + myName + 
      ", balance: " + myBalance + 
      ", interest rate: " + myInterestRate + 
      ",\n number of withdrawals this month: " + myMonthlyWithdrawCount + 
      ", service charges for this month: " + 
      myMonthlyServiceCharges + ", myStatusIsActive: " +
      myStatusIsActive + "]";
   }

我还是Java的新手,所以我想知道是否有办法将%.2f实现到字符串某处以仅格式化myBalance变量。谢谢!

2 个答案:

答案 0 :(得分:1)

使用async: false

String.format(...)

或更简洁:

@Override
public String toString() {
    return "SavingsAccount[owner: " + myName + 
    ", balance: " + String.format("%.2f", myBalance) + 
    ", interest rate: " + String.format("%.2f", myInterestRate) + 
    ",\n number of withdrawals this month: " + myMonthlyWithdrawCount + 
    ", service charges for this month: " + 
    myMonthlyServiceCharges + ", myStatusIsActive: " +
    myStatusIsActive + "]";
}

请注意,khelwood询问我使用@Override public String toString() { String result = String.format("[owner: %s, balance: %.2f, interest rate: %.2f%n" + "number of withdrawals this month: %d, service charges for this month: %.2f, " + "myStatusIsActive: %s]", myName, myBalance, myInterestRate, myMonthlyWithdrawCount, myMonthlyServiceCharges, myStatusIsActive); return result; } 表示新行令牌而不是通常的"%n"字符串。我使用"\n"因为这将允许%n获得特定于平台的新行,特别是如果我想将String写入文件时非常有用。请注意,java.util.Formatter以及String.format(...)和类似方法在后台使用System.out.printf(...),因此这也适用于它们。

答案 1 :(得分:0)

使用String.format()

示例:

Double value = 8.030989;
System.out.println(String.format("%.2f", value));

输出:   8.03