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