Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my calculator adding the digits of its input together instead of updating to a multi-digit number?

I am making a simple calculator and so far its working pretty decently for me besides when I try to enter a digit larger than 9. If I put in 11+55 it will save the firstNumber as 2 and the secondNumber as 10 and return 12 when I obviously want it to save 11 and 55 and return 66.

Thank you in advance to anyone who takes their time to help me out! =)

I’m honestly very new to all of this but am pretty sure the issue is somewhere in my results function at the top of my js file but have been getting majorly confused by it. It seems like it is adding somewhere that it is supposed to be concatenating?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is what I’m working with…

  <body>
    <h2>Calculator</h2>
    <div class="top">
      Output will show up here
      <p id="calculations"></p>
    </div>
    <div class="buttons">  
      <button id="one" onclick="results(1)">1</button>
      <button id="two" onclick="results(2)">2</button>
      <button id="three" onclick="results(3)">3</button>
      <button id="subtraction" onclick="setOperator(`-`)">-</button>
      <button id="four" onclick="results(4)">4</button>
      <button id="five" onclick="results(5)">5</button>
      <button id="six" onclick="results(6)">6</button>
      <button id="addition" onclick="setOperator(`+`)">+</button>
      <button id="seven" onclick="results(7)">7</button>
      <button id="eight" onclick="results(8)">8</button>
      <button id="nine" onclick="results(9)">9</button>
      <button id="divison" onclick="setOperator(`/`)">/</button>
      <button id="zero" onclick="results(0)">0</button>
      <button id="enter" onclick="enterButton()">Enter</button>
      <button id="clear" onclick="clearResults()">Clear</button>
      <button id="mulitplication" onclick="setOperator(`*`)">*</button>
    </div>

  </body>
</html>



let firstNumber = null;
let secondNumber = null;
let operator = null;
let result = null;

function results(input) {
    document.getElementById("calculations").insertAdjacentHTML('beforeend', (input));
  
    if (operator === null) {
      // If operator is null, update firstNumber
      if (firstNumber === null) {
        firstNumber = input;
      } else {
        firstNumber += input;
      }
    } else {
      // If operator is not null, update secondNumber
      if (secondNumber === null) {
        secondNumber = input;
      } else {
        secondNumber += input;
      }
    }
  }


function calculateResult() {
  if (firstNumber === null || secondNumber === null) {
    return null;
  }
  
  const num1 = Number(firstNumber);
  const num2 = Number(secondNumber);
  
  if (isNaN(num1) || isNaN(num2)) {
    return null;
  }

  switch (operator) {
    case "+":
      return Number(firstNumber) + Number(secondNumber);
    case "-":
      return Number(firstNumber) - Number(secondNumber);
    case "*":
      return Number(firstNumber) * Number(secondNumber);
    case "/":
      return Number(firstNumber) / Number(secondNumber);
    default:
      return null;
  }
}

function enterButton() {
  if (result === null) {
  // Calculate the result and update the calculations element
  const result = calculateResult();
  if (result !== null) {
    document.getElementById("calculations").innerHTML = result;
  }
}
    // Set firstNumber to the result, and reset secondNumber and operator
    firstNumber = result;
    secondNumber = null;
    operator = null;
  }

>Solution :

Since you are passing a number to the results() function, in your inline onclick handler for your digits e.g. onclick="results(1)", you will either have to cast the input to a string:

function results(input) {
  document.getElementById("calculations").insertAdjacentHTML('beforeend', input);
  const inputAsString = `${input}`; // cast to a string

  if (operator === null) {
    // If operator is null, update firstNumber
    if (firstNumber === null) {
      firstNumber = inputAsString;
    } else {
      firstNumber += inputAsString; // string concatenation
    }
  } else {
    // If operator is not null, update secondNumber
    if (secondNumber === null) {
      secondNumber = inputAsString;
    } else {
      secondNumber += inputAsString; // string concatenation
    }
  }
}

Or pass in a string (quoted number):

<button id="one" onclick="results('1')">1</button>

Working example

let firstNumber = null;
let secondNumber = null;
let operator = null;
let result = null;

function results(input) {
  document.getElementById("calculations").insertAdjacentHTML('beforeend', input);
  const inputAsString = `${input}`; // cast to a string

  if (operator === null) {
    // If operator is null, update firstNumber
    if (firstNumber === null) {
      firstNumber = inputAsString;
    } else {
      firstNumber += inputAsString;
    }
  } else {
    // If operator is not null, update secondNumber
    if (secondNumber === null) {
      secondNumber = inputAsString;
    } else {
      secondNumber += inputAsString;
    }
  }
}

function clearResults() {
  document.getElementById("calculations").innerHTML = "";
  firstNumber = null;
  secondNumber = null;
  operator = null;
  result = null;
}

function calculateResult() {
  console.log(firstNumber, secondNumber);
  if (firstNumber === null || secondNumber === null) {
    return null;
  }

  const num1 = Number(firstNumber);
  const num2 = Number(secondNumber);

  if (isNaN(num1) || isNaN(num2)) {
    return null;
  }

  switch (operator) {
    case "+":
      return Number(firstNumber) + Number(secondNumber);
    case "-":
      return Number(firstNumber) - Number(secondNumber);
    case "*":
      return Number(firstNumber) * Number(secondNumber);
    case "/":
      return Number(firstNumber) / Number(secondNumber);
    default:
      return null;
  }
}

function enterButton() {
  if (result === null) {
    // Calculate the result and update the calculations element
    const result = calculateResult();
    if (result !== null) {
      document.getElementById("calculations").innerHTML = result;
    }
  }
  // Set firstNumber to the result, and reset secondNumber and operator
  firstNumber = result;
  secondNumber = null;
  operator = null;
}

function setOperator(op) {
  // Set the value of the operator
  if (firstNumber !== null && operator === null) {
    operator = op;
    document.getElementById("calculations").insertAdjacentHTML('beforeend', op);
  } else if (secondNumber !== null && operator !== null) {
    const result = calculateResult();
    if (result !== null) {
      document.getElementById("calculations").innerHTML = result + op;
      firstNumber = result;
      secondNumber = null;
      operator = op;
    }
  } else if (firstNumber !== null && operator !== null && secondNumber === null) {
    operator = op;
    document.getElementById("calculations").innerHTML = firstNumber + op;
  }
}
#calculations {
  min-height: 1rem;
}
<h2>Calculator</h2>
<div class="top">
  Output will show up here
  <p id="calculations"></p>
</div>
<div class="buttons">
  <button id="one" onclick="results(1)">1</button>
  <button id="two" onclick="results(2)">2</button>
  <button id="three" onclick="results(3)">3</button>
  <button id="subtraction" onclick="setOperator(`-`)">-</button>
  <button id="four" onclick="results(4)">4</button>
  <button id="five" onclick="results(5)">5</button>
  <button id="six" onclick="results(6)">6</button>
  <button id="addition" onclick="setOperator(`+`)">+</button>
  <button id="seven" onclick="results(7)">7</button>
  <button id="eight" onclick="results(8)">8</button>
  <button id="nine" onclick="results(9)">9</button>
  <button id="divison" onclick="setOperator(`/`)">/</button>
  <button id="zero" onclick="results(0)">0</button>
  <button id="enter" onclick="enterButton()">Enter</button>
  <button id="clear" onclick="clearResults()">Clear</button>
  <button id="mulitplication" onclick="setOperator(`*`)">*</button>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading