0

Here is the problem I have to answer: (Compare loans with various interest rates) Write a program that lets the user enter the loan amount and loan period in number of years and displays the monthly and total payments for each interest rate starting from 5% to 8%, with an increment of 1/8.

import java.util.Scanner; // Scanner is in java.util
public class FinancialApp {
   public static void main(String[] args) {
     Scanner input = new Scanner(System.in); // Scanner object

     System.out.print("Enter loan amount: "); // input value for loan
      double loanAmount = input.nextDouble();

     System.out.print("Enter number of years as an integer: ");
      int years = input.nextInt();

     System.out.println("Intrest Rate" + "\t" + "Monthly Payment" + "\t" + "Total Payment");

     for(double i = 5.000; i <= 8.000; i += 0.125){

   double monthlyIntrest = i / 1200;
   double monthlyPay = loanAmount * monthlyIntrest / (1 - 1 / Math.pow(1 + monthlyIntrest, years * 12));
   double totalPay = monthlyPay * years * 12;

   System.out.println(i + "%" + "\t" + monthlyPay + "\t" + totalPay);

  }
 }
}
First off I'd like to say that I'm very inexperienced when it comes to coding and my professor hasn't taught us anything at all, so if it could be explained simply I'd really appreciate it. I'm struggling with this class enough. Ok, to the real problem: The code runs, however, it gives me numbers for monthly payment and total payment that have 6+ decimal points and I have no idea how to get it to 2 decimal places. Also, the numbers for the monthly payment are offset to the left (not lined up with the column label).
Sankar
  • 6,908
  • 2
  • 30
  • 53
  • 3
    To simplistically answer your question, it can be acheived like `System.out.printf("%.2f\n", 12345.456);` but really you should not be using `double` for money. Have a look at BigDecimal – Scary Wombat Oct 05 '16 at 06:18
  • Convert your double to BigDecimal and use setScale method. – newuserua_ext Oct 05 '16 at 06:21

1 Answers1

1

First of all, I please you not to use Double for working with money.

You can try do this to have only 2 digits after , : System.out.printf("%.2f", yourNumber);

Sergey Frolov
  • 1,317
  • 1
  • 16
  • 30