2013-07-09 27 views
0

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

下面是当前的代码:(我也知道它不能正常工作,以后会改正)

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 
+0

为什么要对货币使用双http://vanillajava.blogspot.co.uk/2011/08/double-your-money- again.html –

+0

是不是我使用双?你的意思是不使用?我读过这篇文章,谢谢! – andrsnn

+0

有人评论了为什么你不应该使用'双',但我碰巧不同意。大多数投资银行使用long或double而不是BigDecimal(特别是在C++中) –

回答

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); 
+0

真棒我会用printf来实验谢谢! – andrsnn

+0

又为什么8%8.2?为什么不是第一个例子? – andrsnn

+0

@ user2210274'8'填充数字,以便您的列将排队。即它的最小宽度为8.在第一个例子中,你可能不希望在$和数字之间有很多空格。 –

1

检查,如果这有助于 DecimalFormat.getCurrencyInstance(Locale.US).format(doubleValue)