0

I need this specific line to be 2 decimal points.

System.out.println(i + "\t\t" + interest + "\t\t" + principal + "\t\t" + balance);

my entire code is

import java.util.Scanner;
public class assignment5dot22 {

    public static void main(String[] args) {

        int numberOfYears;
        double loanAmount;
        double annualInterest;
        double monthlyInterest;
        double monthlyPayment;
        double principal; 
        double balance;
        double interest;

        Scanner input = new Scanner(System.in);

        System.out.print("Loan Amount: ");
        loanAmount = input.nextDouble();
        System.out.print("Number of Years: ");
        numberOfYears = input.nextInt();
        System.out.print("Annual Interest Rate: ");
        annualInterest = input.nextDouble();

        monthlyInterest = annualInterest / 1200;

        monthlyPayment = loanAmount*monthlyInterest / (1 - (Math.pow(1 / (1 + monthlyInterest),
                numberOfYears * 12)));
        balance = loanAmount;

        System.out.println("Monthly Payment: "
                + (monthlyPayment * 100) / 100.0);
        System.out.println("Total Payment: "
                + (monthlyPayment * 12 * numberOfYears * 100) / 100.0);

        System.out.println("\nPayment#\tInterest\tPrincipal\tBalance");

        for (int i = 1; i <= numberOfYears * 12; i++) {
            interest = (monthlyInterest * balance);
            principal = ((monthlyPayment - interest)*100) / 100.0;
            balance = ((balance - principal) * 100) / 100.0;

            System.out.println(i + "\t\t" + interest + "\t\t" + principal + "\t\t" + balance);
        }
    }


}
Satan Pandeya
  • 3,460
  • 4
  • 22
  • 47
Madison
  • 7
  • 3

2 Answers2

1

I'd suggest trying to use String.format() for your output.

e.g.

System.out.println(String.format("%d \t\t %.2f \t\t %.2f \t\t %.2f", i, interest, principal, balance);

String.format allows you use %d and %.2f to explicitly state the format of your data (integer and float respectively)

EdP
  • 21
  • 1
  • You can also use `printf` like `System.out.printf("%d \t\t %.2f \t\t %.2f \t\t %.2f%n", i, interest, principal, balance);` – saka1029 Jun 19 '20 at 03:02
0

In these situations you could use String.format or directly use System.out.printf() like so:

System.out.printf("%d \t\t %.2f \t\t %.2f \t\t %.2f\n", i, interest, principal, balance);

For these cases it's more readable and concise.

AminM
  • 465
  • 2
  • 8