Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have following program to calculate Bank Transactions and I am having problem

ID: 3756905 • Letter: I

Question

I have following program to calculate Bank Transactions and I am having problem with print statement to two decimal place. i.e. Balance prints $1000.0 and should print $1000.00. Can you help?

package atmsimulator;
import java.util.Scanner;
/**
*

*/

public class AtmSimulator {
  
//initial balance and it is static so that it can be shared throughout program

static double balance=1000.00d;

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);


while(true){

System.out.println("Enter the number of your desired transaction type:");

System.out.println("1. Balance 2. Deposit 3. Withdrawal 4. Quit");

int choice = scan.nextInt();

if (choice == 1){

System.out.println("Your current balance is $" +balance+".");

}

else if(choice == 2){

System.out.println("Enter the amount of the deposit:");

double deposit = scan.nextDouble();

balance = balance + deposit;

System.out.println("Your current balance is $" +balance+ ".");

}

else if(choice == 3){

System.out.println("Enter the amount of the withdrawal:");

double withdrawal = scan.nextDouble();

if(withdrawal <= balance){

balance = balance - withdrawal;

}

else{

System.out.println("Insufficient funds.");

}

System.out.println("Your current balance is $" +balance+ ".");

}

else if(choice == 4){

System.out.println("Good-bye.");

break;

}
}
}
}

Explanation / Answer

There are multiple ways to control output formatting, you can go with the use of String.format as the following:

Note: Let 1.9999 be the value we want to control the precision for upto 2 places after the decimal point.

String strDouble = String.format("%.2f", 1.9999);

System.out.println(strDouble); // --> This prints 2.00


you can change %.2f to include the required digits of precision.

Another way to do this is with DecimalFormat as the following:

You can explore the respective function for furthe details if required.