2015-07-21 270 views
0

我正在處理的項目需要使用toString方法打印銀行帳戶餘額。我不允許在我的當前程序中添加任何方法,但是我需要將我的myBalance變量格式化爲一個double而不是一個小數點後兩位。在這個特定的例子中,我的程序應該打印8.03,但是打印8.0。Java - toString格式(格式化雙精度)

這裏是我的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變量。謝謝!

回答

1

使用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 + "]"; 
} 

或更簡潔:

@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; 
} 

注意khelwood問起我使用的"%n"新線標記,而不是通常"\n"字符串。我使用%n,因爲這將允許java.util.Formatter獲取平臺特定的新行,特別是在我想將字符串寫入文件時非常有用。請注意0​​以及System.out.printf(...)和類似的方法在後臺使用java.util.Formatter,所以這也適用於它們。

+0

我明白了!我不知道你可以這樣寫。非常感謝您的先生/女士。另外,我愛你的用戶名。 – Trafton

+0

@Trafton:請參閱更新 –

+0

你的意思是'\ n'你有'%n'嗎? – khelwood

0

使用的String.format()

例子:

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

輸出: 8.03

+0

[link]的可能重複(http://stackoverflow.com/questions/4885254/string-format-to-format-double-in-java) – digidude