gpt4 book ai didi

java - 试图在java中四舍五入到两位小数

转载 作者:行者123 更新时间:2023-12-04 05:26:50 25 4
gpt4 key购买 nike

System.printf("%.2f", currentBalance) 工作正常,但问题是四舍五入的数字出现在句子之后。将代码放入你的 eclipse 程序并运行它,你可以看到肯定有问题。如果有人可以提供帮助,将不胜感激。

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

}

最佳答案

请试试这个

import java.text.DecimalFormat;



public class Visitor {


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 "+Double.parseDouble(new DecimalFormat("#.##").format(currentBalance)));


currentBalance = currentBalance + (currentBalance * interestRate);
}
System.out.println ("Your final balance after 10 years is " + currentBalance);
return currentBalance;
}
}

关于java - 试图在java中四舍五入到两位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13105847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com