skip to Main Content

When creating a calculator generally using a switch statement works for adding,subtracting etc, in this scenario I am not sure where the Switch statement would go or if its needed, so that the calculator can do its mathematics?

const screen = document.getElementById('screen');
const btn = document.querySelectorAll('.btn');
for (const btns of btn) {
  //press button by index
  btns.addEventListener("click", (num) => {
    const numValue = num.target.innerText;
    const textNode = document.createTextNode(numValue);

    if(numValue === "="){
      
    }

    screen.appendChild(textNode)
    
  });
  
}
switch(numValue){
      case "+":
        num + num
        break;
      case "-":
        num - num
        break;
      case "/":
        num / num
        break;
      case "*":
        num * num
        break;
      case "*":
        num - num
        break;
      default:
        console.log("Error")
    }
<div id="screen"></div>
<div>
<button class="btn">+</button>

2

Answers


  1. In order to perform mathematics when the "=" button is pressed in a calculator, you need to keep track of the numbers and the operation to perform like this.

    let currentValue = ""; // Variable to store the current value
    let oldValue = ""; // Variable to store the previous value
    let operation = ""; // Variable to store the operation
    
    const pressNumber = number => {
      currentValue += number;
      document.getElementById("screen").value = currentValue;
    }
    
    const pressOperator = operator => {
      operation = operator;
      oldValue = currentValue;
      currentValue = "";
    }
    
    const calculate = () => {
      const num1 = parseFloat(oldValue);
      const num2 = parseFloat(currentValue);
      let result;
    
      switch (operation) {
        case "+":
          result = num1 + num2;
          break;
        case "-":
          result = num1 - num2;
          break;
        case "*":
          result = num1 * num2;
          break;
        case "/":
          result = num1 / num2;
          break;
        default:
          result = "Error";
          break;
      }
    
      document.getElementById("screen").value = result;
      currentValue = "";
      oldValue = "";
      operation = "";
    }
    
    const clearScreen = () => {
      document.getElementById("screen").value = "";
      currentValue = "";
      oldValue = "";
      operation = "";
    }
    <!DOCTYPE html>
    <html>
    <head>
      <title>Simple Calculator</title>
    </head>
    <body>
      <input type="text" id="screen" readonly>
      <br>
      <button onclick="pressNumber(1)">1</button>
      <button onclick="pressNumber(2)">2</button>
      <button onclick="pressNumber(3)">3</button>
      <br>
      <button onclick="pressNumber(4)">4</button>
      <button onclick="pressNumber(5)">5</button>
      <button onclick="pressNumber(6)">6</button>
      <br>
      <button onclick="pressNumber(7)">7</button>
      <button onclick="pressNumber(8)">8</button>
      <button onclick="pressNumber(9)">9</button>
      <br>
      <button onclick="pressOperator('+')">+</button>
      <button onclick="pressOperator('-')">-</button>
      <button onclick="pressOperator('*')">*</button>
      <br>
      <button onclick="pressOperator('/')">/</button>
      <button onclick="calculate()">=</button>
      <button onclick="clearScreen()">C</button>
    
    </body>
    
    </html>

    I have two variables currentNumber and operation that keep track of the current number and the operation to be performed.

    When a calculator button is clicked, we check if it is a number or an operation symbol.

    If it’s a number, we concatenate it to the currentNumber variable.

    If it’s an operation symbol, we store it in the operation variable.

    When the "=" button is pressed, we call the calculate function passing the current number, the number on the screen, and the operation.

    The calculate function uses a switch statement to perform the correct operation based on the operation variable.

    Login or Signup to reply.
  2. You can try the following way:

    const screen = document.getElementById("screen");
    const buttons = document.querySelectorAll("button");
    
    let currentInput = "";
    
    //add event listeners to all buttons
    for (const btn of buttons) {
      btn.addEventListener("click", (event) => {
      //get the text content of the clicked button
        const buttonText = event.target.innerText;
        //check the button pressed
        switch (buttonText) {
          case "=":
            //if "=" is pressed, calculate the result
            const result = calculateResult(currentInput);
            screen.value = result;
            currentInput = result;
            break;
          case "+":
          case "-":
          case "*":
          case "/":
            //append the operator to the current input
            currentInput += ` ${buttonText} `;
            screen.value = currentInput;
            break;
          default:
            //append the pressed button value to the current input
            currentInput += buttonText;
            screen.value = currentInput;
        }
      });
    }
    
    function calculateResult(input) {
      try {
        return Function(`'use strict'; return (${input})`)();
      } catch (error) {
        return "Error";
      }
    }
    div {
      text-align: center;
    }
    
    input {
      box-sizing: border-box;
      margin-bottom: 3px;
      font-size: 14px;
    }
    
    button {
      font-size: 14px;
      margin: 3px;
      cursor: pointer;
      width: 30px;
      height: 30px;
    }
    <div>
      <input type="text" id="screen" readonly>
      <div>
        <button>1</button>
        <button>2</button>
        <button>3</button>
        <button>+</button>
        <br>
        <button>4</button>
        <button>5</button>
        <button>6</button>
        <button>-</button>
        <br>
        <button>7</button>
        <button>8</button>
        <button>9</button>
        <button>*</button>
        <br>
        <button>0</button>
        <button>/</button>
        <button>=</button>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search