Search code examples
javafloating-pointfloating-point-precision

How to ensure that my double output is ONLY 2 decimal places?


I am working on a class project that is suppose to be a ATM machine. The parameters for the project are to have 5 methods and a main program. Everything seems to be working fine, but upon further testing, and depositing more money, the new balance turns into a figure with about 16 decimal places. I'm not using any division and the methods are simple add and subtract arithmetic.

This is basically what I am getting after a number of deposits.

Enter the number for one of the following choices.
 1. Display Balance
 2. Deposit
 3. Withdraw
 4. Log Out
2
Enter the amount you wish to deposit: $ 222.22

$ 2943.48

Enter the number for one of the following choices.
 1. Display Balance
 2. Deposit
 3. Withdraw
 4. Log Out
2
Enter the amount you wish to deposit: $ 333.22

$ 3276.7

Enter the number for one of the following choices.
 1. Display Balance
 2. Deposit
 3. Withdraw
 4. Log Out
2
Enter the amount you wish to deposit: $ 222.33

$ 3499.0299999999997

Enter the number for one of the following choices.
 1. Display Balance
 2. Deposit
 3. Withdraw
 4. Log Out

This is my current code and what I have done. Thanks for the help.

import java.util.Scanner;

public class ATM {

public static Scanner keyboard = new Scanner(System.in);
// The checkID method determines if acctNum is a valid account number
// and pwd is the correct password for the account.  If the account information
// is valid, the method returns the current account balance, as a string.
// If the account information is invalid, the method returns the string "error".
public static String checkID(String acctNum, String pwd)
{
    String result = "error";


    // Strings a, b, and c contain the valid account numbers and passwords.
    // For each string, the account number is listed first, followed by
    // a space, followed by the password for the account, followed by a space,
    // followed by the current balance.
    String a = "44567-5 mypassword 520.36";
    String b = "1234567-6 anotherpassword 48.20";
    String c = "4321-0 betterpassword 96.74";

    if (acctNum.equals(a.substring(0, a.indexOf(" "))) && 
            pwd.equals(a.substring(a.indexOf(" ")+1,a.lastIndexOf(" "))))
        return result = a.substring(a.lastIndexOf(" ") + 1);

    if (acctNum.equals(b.substring(0, b.indexOf(" "))) && 
            pwd.equals(b.substring(b.indexOf(" ")+1,b.lastIndexOf(" "))))
        return result = b.substring(b.lastIndexOf(" ") + 1);

    if (acctNum.equals(c.substring(0, c.indexOf(" "))) && 
            pwd.equals(c.substring(c.indexOf(" ") + 1,c.lastIndexOf(" "))))
        return result = c.substring(c.lastIndexOf(" ") + 1);

    return result;
}
public static int menu()
{
    int menuChoice;
    do
    { 
        System.out.print("\nEnter a number corresponding to one of the"
                + " following choices.\n 1. Display Balance"
                + "\n 2. Deposit\n 3. Withdraw\n 4. Log Out\n");
        menuChoice = keyboard.nextInt();
        if (menuChoice < 1 || menuChoice > 4){
            System.out.println("error");
        }
    }while (menuChoice < 1 || menuChoice > 4);
    return menuChoice;
}
public static void displayBalance(double x)
{
    System.out.printf("\nYour current balance is $%.2f\n", x);
}
public static double deposit(double x, double y)
{
    return x + y;
}
public static double withdraw(double x, double y)
{
    if (y > x){
        return x;
    }
    return x-y;
}
public static void main(String[] args) {

    String accNum, pass, origBal = "error";
    int count = 0, menuOption = 0;
    double depositAmt, withdrawAmt, currentBal; 

    //loop that will count the number of login attempts
    //you make and will exit program if it is more than 3.
    //as long as oriBal equals an error.  
    do{

        System.out.println("Please enter your account number: ");
        accNum = keyboard.next();

        System.out.println("Enter your password: ");
        pass = keyboard.next();

        origBal = checkID(accNum, pass);

        count++;
        if (count >= 3 && origBal.equals("error")){
            System.out.print("Maximum login attempts reached.");
            System.exit(0);
        }
        if (!(origBal.equals("error"))){
            System.out.println("\nYour balance is $ "+ origBal);
        }
        else
            System.out.println(origBal);


    }while(origBal.equals("error"));

    currentBal=Double.parseDouble(origBal);
    //this loop will keep track of the options that 
    //the user inputs in for the menu. and will 
    //give the option of deposit, withdraw, or logout.

    while (menuOption != 4)
    { 
        menuOption=menu();
        switch (menuOption)
        {
        case 1:
            displayBalance(currentBal);
            break;
        case 2:
            System.out.print("Enter the amount you wish to deposit: $ ");
            depositAmt = keyboard.nextDouble();
            currentBal = deposit(depositAmt, currentBal);
            System.out.printf("Your new balance is $%.2f\n",  currentBal);
            break;
        case 3:
            System.out.print("Enter the amount you wish to withdraw: $ ");
            withdrawAmt = keyboard.nextDouble();
            if (withdrawAmt > currentBal)
                System.out.println("error");
            currentBal = withdraw(currentBal, withdrawAmt);
            System.out.printf("Your new balance is $%.2f\n",currentBal);
            break;
        case 4:
            System.exit(0);
            break;
        }
    }
}

}

This is my updated version.

Thanks for the suggestions.


Solution

  • I suggest you read on working with Currency in java -- one of the things it mentions is to avoid using float or double to represent money, since these data types are not as well-suited to rounding off as, say, the recommended BigDecimal.