My task is to create a mortgage calculator that accepts the principal, interest rate, and loan length. It would then display back the expected monthly payment and totaled interest paid. I'm also trying to do this using a static method. When I run it the monthly payment and totaled interest display $NaN
. I don't think my formula is wrong because when I calculated it with a calculator, I got the correct answer.
For example, a principle of $53,000, interest rate of 7.625%, and a term of 15 years, should display a monthly payment of $495.09, and a totaled interest paid of $36,155.99.
Current code:
public class FinanceCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//Asking user which calculator they want to use
System.out.println("Which calculator would you like to use? (1)Mortgage, (2)Future Value");
byte userIn = scanner.nextByte();
//Creating if statements for each calculator
if(userIn == 1) {
System.out.println("Enter the principle: ");
float principle = scanner.nextFloat();
System.out.println("Enter interest rate: ");
float intRate = scanner.nextFloat();
System.out.println("Enter loan length(In Years):" );
int loanTerm = scanner.nextInt();
float monthlyMortgage = (float) mortgageCalc(principle, intRate, loanTerm);
float totaledInterest = ((loanTerm * 12 * monthlyMortgage) - principle);
System.out.println("A $" + principle + " loan at " + intRate + "% interest for " + loanTerm + "years would have a $" + monthlyMortgage + "/mo payment with " +
"a total interest of $" + totaledInterest);
}
}
//Creating mortgage calculator, Calculating monthly mortgage
public static double mortgageCalc(float loan, float rate, int term) {
float decimalIntRate = rate * 100;
float mortgage = (float) ((((loan * (decimalIntRate / 12)) * Math.pow(1 + (decimalIntRate / 12), 12 * term)) / Math.pow(1 + (decimalIntRate / 12), 12 * term)) - 1);
return mortgage;
}
}
The result I want it to display is
A $53000.0 loan at 7.625% interest for 15years would have a $495.09/mo payment with a total interest of $36155.99
Try it like this.
double i = .07625/12; // interest per month
double p = 53_000; // principal
double n = 180; // number of payments (15 years x 12 months/year)
double mort = p*i*Math.pow(1+i, n)/(Math.pow(1+i, n)-1);
System.out.printf("Mort = $%.2f%n",mort);
System.out.printf("Total Interest = $%.2f%n",mort*n-p);
prints
Mort = $495.09
Total Interest = $36115.99
Your parentheses were off in your calc method. And you multiplied the annual interest rate by 100
instead of dividing. Since Math.pow
returns a double
I would just stick with that and not use float
.
public static double mortgageCalc(double loan, double rate, int term) {
double decimalIntRate = rate / 100;
double mortgage = (double) loan * (decimalIntRate / 12)*
(Math.pow(1 + (decimalIntRate / 12), 12 * term)
/ (Math.pow(1 + (decimalIntRate / 12), 12 * term) - 1));
return mortgage;
}