System.printf(「%。2f」,currentBalance)工作正常,但問題出現在句子後面的舍入數字。把代碼放到你的eclipse程序中並運行它,你可以看到一些肯定是錯誤的。如果有人能幫助它,將不勝感激。嘗試在java中舍入到小數點後兩位數
public class BankCompound {
public static void main (String[] args) {
compound (0.5, 1500, 1);
}
public static double compound (double interestRate, double currentBalance, int year) {
for (; year <= 9 ; year ++) {
System.out.println ("At year " + year + ", your total amount of money is ");
System.out.printf("%.2f", currentBalance);
currentBalance = currentBalance + (currentBalance * interestRate);
}
System.out.println ("Your final balance after 10 years is " + currentBalance);
return currentBalance;
}
}
DecimalFormat是要走的路。如果您反覆使用相同的格式,請將DecimalFormat設置爲靜態最終值並重新使用它以提高效率。 – AWT