kabloo12
kabloo12

Reputation: 37

Formatting decimal places while formatting System.out.print Java

Hey guys I dug for a while but couldn't manage to find a related question for this topic. I'm writing a program that outputs a table that lists the minimum payment and balance for a credit card user. The problem occurs in the last part of the code where I have to put spaces between the output as well as format the output to 2 decimal places.

Thanks in advance!

My code:

 public static void main(String[] args) {

        double minPay = 0; 

        Scanner key = new Scanner(System.in); 
        System.out.printf("Please Enter your credit card balance: ");
        double balance = key.nextDouble();
        System.out.printf("Please Enter your monthly interest rate: ");
        double rate = key.nextDouble();

        System.out.printf("%-6s%-10s%-10s\n", "", "Min.Pmt", "New Balance");
        System.out.printf("------------------------------\n"); 
        for (int i=0; i<12; i++){
        minPay = balance*0.03; 

        if (minPay<10){
            minPay=10.00; 
        }

        double add = (balance*(rate/100));
        balance += add; 
        balance -= minPay; 
        System.out.printf("%-6s%-10.2f%-10.2f\n", i+1 + ".", "$" + minPay, "$" + balance);

Upvotes: 1

Views: 630

Answers (2)

Raju Rathore
Raju Rathore

Reputation: 149

Use DecimalFormat to format any number

DecimalFormat df = new DecimalFormat("0.00");
String result = df.format(44.4549);

Upvotes: 0

Rob Crawford
Rob Crawford

Reputation: 556

In the last line, you're creating two strings for the printf arguments, instead of the floats the format string expects. In Java, when you "add" a string to something, the other argument gets converted to a string and the result is another string.

Move the dollar signs into the printf format string and just pass the arguments as floats.

Upvotes: 1

Related Questions