Issues with adding in Java Calculator

Issues with adding in Java Calculator
0.0 0

#1

Here’s my codepen: https://codepen.io/HowlCalcifer/pen/mByOdo?editors=0010

every other operator seems to work besides addition. I just need a second pair of eyes to let me know what’s wrong.


#2

In the for loop within the click event handler for the div with id=“equal”, you have:

num2 = str.slice(0, regIndx2);

After this line above runs, num2 contains a string value.

A few lines later, you have:

        else if (operator == "+") {
          sum = sum + num2;
        }

The variable sum is also a string, so when you use the + operator between two strings, you concatenate the two strings together. You should modify your solution so that sum and num2 are always numbers.


#3

Thank you for checking! using parsefloat() works like a charm


#4

FYI - You could replace 10 click events (one for each number clicked) with one click event for all the elements containing numbers. This can be accomplished by adding an extra class name to button elements with the numbers 0-9.

For example, the current html for the number 7 button (shown below):

<button class="calcButton" id="seven">7</button>

would become:

<button class="calcButton num" id="seven">7</button>

With this new class name (num is what I chose), you can use one event handler for all the buttons with class=“num”:

  $(".num").click(function() {
    x.push($(this).text());
    str = x.join("");
    $("#myText").text(str);
  });

You will notice that I used JQuery for all of the above function, instead of mixing vanilla JS with JQuery.


#5

Thank you for the example I’ll try it out!