【问题标题】:how to get this to display 2 decimal points? [duplicate]如何让它显示2个小数点? [复制]
【发布时间】:2020-10-09 05:34:18
【问题描述】:

我需要这个特定的行是 2 个小数点。

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

我的整个代码是

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);
        }
    }


}

【问题讨论】:

    标签: java


    【解决方案1】:

    我建议尝试使用 String.format() 作为您的输出。

    例如

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

    String.format 允许您使用 %d 和 %.2f 明确说明数据的格式(分别为整数和浮点数)

    【讨论】:

    • 你也可以像System.out.printf("%d \t\t %.2f \t\t %.2f \t\t %.2f%n", i, interest, principal, balance);一样使用printf
    【解决方案2】:

    在这些情况下,您可以使用 String.format 或直接使用 System.out.printf(),如下所示:

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

    对于这些情况,它更具可读性和简洁性。

    【讨论】:

      猜你喜欢
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 2014-07-15
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      相关资源
      最近更新 更多