0

I'm making a calulator programme in java with a GUI on swing. My calculator after an operation, lets say multiplying throws out a double and even if there are no decimal places, the number looks for ex. like this: 2 * 2 = 4,0. I was wondering if there's a way to make the programme detect if it needs to show the decimal or not, so if the number is an integer it would show a whole number like: 2 * 2 = 4. I've try doing it this way:

JButton btnEquals = new JButton("=");
        btnEquals.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                SecondNum = Double.parseDouble(txtDisplay.getText());
                if (operation == "+") {
                    txtDisplay.setText(String.valueOf(FirstNum + SecondNum));
                    if ((FirstNum + SecondNum) == Integer.parseInt(String.valueOf(FirstNum + SecondNum))){
                        txtDisplay.setText(String.valueOf(Integer.parseInt(String.valueOf(FirstNum + SecondNum))));
                    }
                }
            }

inside the firs "if" i've made a second one wher if the double result of First Number and second number is equal to the integer equivalent of this operation, the the display should show the integer form, sinc double is not need. This does not work, the programme crashes.

Bruno
  • 92
  • 1
  • 8
  • 1
    https://stackoverflow.com/questions/11826439/show-decimal-of-a-double-only-when-needed should do what you need. DecimalFormat can render only the decimal places that are needed – chemicalcrux Jun 27 '18 at 21:52
  • What @chemicalcrux says. Also this is bad: `if (operation == "+") {`. You do not want to compare Strings using `==` or `!=` but rather should use the `.equals(...)` method since you don't want to compare for *reference equality*, that two Strings represent the very same object, but rather *functional equality`, that two Strings have the same characters in the same order. – Hovercraft Full Of Eels Jun 27 '18 at 22:01

1 Answers1

0

Right now you are parsing SecondNum into a double which is why you are getting a double result. I would use a modulus operator %. If (sumResult % 1 != 0) than you know that it needs the decimal place and you should parse double. If it does == 0 than you can parse integer.

Josh
  • 386
  • 5
  • 14