如何确保我的双输出只有2位小数?

时间:2014-11-02 22:46:42

标签: java floating-point floating-point-precision

我正在研究一个假定为ATM机的课程项目。项目的参数有5个方法和一个主程序。一切似乎都运转良好,但经过进一步的测试,并存入更多的钱,新的余额变成了一个大约16位小数的数字。我没有使用任何除法,方法是简单的加法和减法算法。

这基本上是我在多次存款后获得的。

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

这是我目前的代码和我所做的。谢谢您的帮助。

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

}

这是我的更新版本。

感谢您的建议。

4 个答案:

答案 0 :(得分:1)

如果您不需要使用double,请考虑使用比例2切换到BigDecimal。与double不同,BigDecimal可以完全代表您的所有输入和结果。它是大多数货币计算的更好选择,包括ATM模拟。

答案 1 :(得分:0)

您获得的浮点错误是由于数字存储在内存中的方式,更多信息herehere

要回答您的问题,请使用格式,例如:

DecimalFormat df = new DecimalFormat("#.00");
System.out.println("\nYour current balance is $" + df.format(currentBal) + "\n");

分别在其他地方改变。

答案 2 :(得分:0)

您可以使用printf()功能。

System.out.printf("Your current balance is $%.2f\n", currentBal);

进一步说明:

printf功能将打印格式化输出。 %是您要打印的变量的开头,.2告诉您想要在小数位后显示两个插槽的函数,f表示您的变量是什么类型的变量#39;重新给出(在这种情况下,f为浮点/双精度值)。该类型也表示输入的结束,因此&#34; \ n&#34;作为格式化的一部分,它不会被归入,并且仍然是正常的换行符。

注意: printf函数也会进行修正随机十进制数所需的舍入。如果是3499.0299999999997,则会打印3499.03

答案 3 :(得分:0)

我建议你阅读working with Currency in java - 其中提到的一件事是避免使用float或double来表示金钱,因为这些数据类型不太适合四舍五入,比如,推荐BigDecimal。