0

我正在为一个班级写一个简单的贷款计算器。我正在尝试以美元形式返回金额。我找到了 system.out.printf(); 但似乎无法使其正常工作。

这是当前代码:(我也知道它不能正常工作,稍后会修复)

public static void calculate() {

    annualInterest = (annualInterest * 0.01) / 12; //percentage to decimal then to month interest %
    term = term * 12;
    double payment = amtBorrowed * annualInterest;

    double temp = 1/(1 + annualInterest);
    temp = Math.pow(temp,term);
    temp = 1 - temp;

    payment = payment / temp;
    double Interest = amtBorrowed * annualInterest;
    double principal = payment - Interest;

    System.out.println("Your monthly payment is " + payment);
    System.out.println("          | Interest | principal");
    System.out.println("Month 1 :" +"   "+ Interest + " " + principal);
    for (int i = 2; i < term + 1; i ++){
        System.out.print("Month "+ i + " :");
        amtBorrowed = amtBorrowed - (Interest + principal);
        payment = amtBorrowed * annualInterest;
        temp = 1/(1 + annualInterest);
        temp = Math.pow(temp,term);
        temp = 1 - temp;
        payment = payment / temp;
        Interest = amtBorrowed * annualInterest;
        principal = payment - Interest;
        System.out.println("   " + Interest + "    " + principal);
    }
}

输出:

Your monthly payment is 4432.061025275802
          | Interest | principal
Month 1 :   500.0 3932.0610252758024
Month 2 :   477.839694873621    3757.789681084494
Month 3 :   456.6615479938304    3591.242149217312
Month 4 :   436.4220295077747    3432.0761055985745
Month 5 :   417.079538832243    3279.9643981645363
Month 6 :   398.5943191472591    3134.594374430564
4

2 回答 2

3

改用 printf

System.out.printf("Your monthly payment is $%.2f%n", payment);

这应该打印

Your monthly payment is $4432.06

System.out.printf(" %8.2f %8.2f%n", Interest, principal);
于 2013-07-09T23:48:19.993 回答
1

检查这是否有帮助 DecimalFormat.getCurrencyInstance(Locale.US).format(doubleValue)

于 2013-07-09T23:54:22.050 回答