你如何正确地使用BigDecimal变量?

时间:2013-12-08 05:55:11

标签: java bigdecimal

我一直在研究一个小程序,在它中按一个按钮,它会将.1添加到变量中。我一直在使用双倍,我不断得到超长小数(例如12.0000000000000001)。在谷歌搜索问题之后,我想出了BigDecimal类。我以前从未使用过这门课,所以我需要帮助。我的问题是如何解决这个问题?

这是我的代码(我有2个类,这是我的主要类):

    public class Game extends JFrame {
private static final long serialVersionUID = 1L;

private static mainGame mainGame = new mainGame();

private static JPanel upgradeScreen = new JPanel();

private static JTabbedPane pane = new JTabbedPane();
    public static int createRate = 16;
public static double cost = 0.1;
public static int stuff = 0;
public static double  cash = 0;
public static int limit = 1000;

public static JLabel lblMoney2 = new JLabel("You have: " + cash + " Dollars to spend.");

public Game() {

    setTitle("Shooter Tycoon");
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(1100, 688);
    setLocationRelativeTo(null);

    pane.add("Main", mainGame);
    pane.add("Upgrades", upgradeScreen);
    upgradeScreen.setLayout(null);

    lblMoney2.setBounds(10, 11, 325, 14);
    upgradeScreen.add(lblMoney2);

    getContentPane().add(pane);

}

// The main method

public static void main(String[] args) {

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Game frame = new Game();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public static void add() {

    if (stuff + createRate < limit) {
        stuff += createRate;
    }
    mainGame.lblStuff.setText("You have made " + stuff + " of " + limit + " Things!");
}

public static void sell() {
    if (stuff > 0) {
        cash += stuff * cost;
        stuff = 0;
        mainGame.lblMoney.setText("You have made " + cash + " Dollars!");
        mainGame.lblStuff.setText("You have made " + stuff + " of " + limit + " Things!");
        lblMoney2.setText("You have: " + cash + " Dollars to spend.");
    }

}
  }

我还是比较新的Java,所以不要太难评判我。如果可以在不使用BigDecimal的情况下解决这个问题,那么一定要使用它。提前谢谢。

1 个答案:

答案 0 :(得分:0)

在这种特殊情况下,您正在使用资金,因此您可以通过将分数存储为整数而不是以小数表示的美元数来避免整个BigDecimak问题。要将美元值显示为字符串,请使用:

String value="$"+(cents/100)+"."+(cents%100);

请注意,当cents%100介于0和9之间时,您还需要考虑特殊情况,因此您需要将此代码放在方法中。如果您需要更多详细信息,请与我们联系。