Reputation: 1621
I am writing a simple loan calculator for a class. I am attempting to have the amounts return in dollar form. I have found system.out.printf(); but cannot seem to make it work properly.
Here is the current code: (I am also aware it doesn't work correctly, will fix later)
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);
}
}
Output:
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
Upvotes: 0
Views: 421
Reputation: 97
check if this helps
DecimalFormat.getCurrencyInstance(Locale.US).format(doubleValue)
Upvotes: 1
Reputation: 533442
Using printf instead
System.out.printf("Your monthly payment is $%.2f%n", payment);
This should print
Your monthly payment is $4432.06
Also
System.out.printf(" %8.2f %8.2f%n", Interest, principal);
Upvotes: 3