Java,格式化为美元价值的两倍

时间:2013-07-09 23:45:00

标签: java jvm jgrasp

我正在为一堂课写一个简单的贷款计算器。我试图以美元形式返还金额。我找到了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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

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