Question

I have been working on a small program, in it you press a button and it adds .1 to a variable. I've been using a double and I keep getting super long decimals(such as 12.0000000000000001). After googling the issue I came up with the BigDecimal class. I've never used the class before so I need help. My question is how do I fix this issue?

Here's my code (I have 2 classes, this is my main class):

    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.");
    }

}
  }

I'm still relatively new to Java so don't judge me too hard. If it is possible to solve this without using BigDecimal then by all means use it. Thanks in advance.

Était-ce utile?

La solution

In this particular case, you're working with money, so you can avoid the whole BigDecimak issue by just storing the number of cents as an integer instead of the number of dollars as a decimal. To display the dollar value as a string use:

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

Note that you'll also need to account for the special case when cents%100 is between 0 and 9, so you'll want to put this code inside a method. Let me know if you need more details.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top