What is the best way to showcase the outcomes of arithmetic calculations on my calculator?

In the midst of creating a calculator, I have encountered some issues in getting it to display the correct result. Despite successfully storing the numbers clicked into separate variables, I am struggling with showing the accurate calculation outcome.

let numIni = "";
let numSub = "";
let op = "";
let calcResult = false;
//const text = display.innerText;
let result = 0;
clr();


//basic addition
function addition(numIni, numSub) {
  return parseFloat(numIni) + parseFloat(numSub);

}

//basic subtraction
function subtraction(numIni, numIni) {
  parseFloat(numIni) - parseFloat(numIni);
}

//basic Multiplication
function multiply(numIni, numIni) {
  parseFloat(numIni) * parseFloat(numIni);
}

//basic division
function divide(numIni, numIni) {
  parseFloat(numIni) / parseFloat(numIni);
}

//operator function
function operate(op) {
  let result;
  switch (op) {
    case "+":
      result = addition(numIni, numSub);
      break;
    case "-":
      result = subtraction(numIni, numIni);
      break;
    case "*":
      result = multiply(numIni, numIni);
      break;
    case "/":
      if (numSub == 0) {
        return "Can't do that";
      } else {
        result = divide(numIni, numIni);
      }
    default:
      return "Null";
  }
}
//button display functions
function disNum(val) {
  if (numIni == "") {
    parseFloat(document.getElementById("display").value += val);
    numIni = parseFloat(val);
  } else {
    parseFloat(document.getElementById("display").value += val);
    numSub = parseFloat(val);
  }

}

function disOp(val) {
  document.getElementById("display").value += val;
  return op = val;
}

function clr() {
  return document.getElementById("display").value = "";
}

function equal() {
  operate(numIni, numSub);
  document.getElementById("display").value = result;
}
<head>Calc</head>
<div>
  <input type="text" id="display">
</div>

<input type="button" value="0" onClick="disNum('0')">
<input type="button" value="1" onClick="disNum('1')">
<input type="button" value="2" onClick="disNum('2')">
<input type="button" value="3" onClick="disNum('3')">
<input type="button" value="4" onClick="disNum('4')">
<input type="button" value="5" onClick="disNum('5')">
<input type="button" value="6" onClick="disNum('6')">
<input type="button" value="7" onClick="disNum('7')">
<input type="button" value="8" onClick="disNum('8')">
<input type="button" value="9" onClick="disNum('9')">
<input type="button" value="+" onClick="disOp('+')">
<input type="button" value="-" onClick="disOp('-')">
<input type="button" value="*" onClick="disOp('*')">
<input type="button" value="/" onClick="disOp('/')">
<input type="button" value="=" onClick="equal()">
<input type="button" value="Clr" onClick="clr()">

Answer №1

I've made significant updates to the code by introducing a new input field to store the last result, along with the initial number and previous operator. This helps in streamlining the global variables and minimizing unwanted alterations.

Now, whenever an operator is clicked, the system checks for any previous result and operator, retrieves the number from the display input, performs the necessary arithmetic operation, and stores the result along with the current operator (if applicable).

Although I have conducted tests, there could still be potential bugs that need to be addressed.

let display = document.querySelector('#display');
let res = document.querySelector('#result');
clr();

//basic addition
function addition(numIni, numSub) {
  return parseFloat(numIni) + parseFloat(numSub);
}

//basic subtraction
function subtraction(numIni, numSub) {
  return parseFloat(numIni) - parseFloat(numSub);
}

//basic Multiplication
function multiply(numIni, numSub) {
  return parseFloat(numIni) * parseFloat(numSub);
}

//basic division
function divide(numIni, numSub) {
  return parseFloat(numIni) / parseFloat(numSub);
}

//operator function
function operate(op, numIni, numSub) {
  let result = 0;
  switch (op) {
    case "+":
      result = addition(numIni, numSub);
      break;
    case "-":
      result = subtraction(numIni, numSub);
      break;
    case "*":
      result = multiply(numIni, numSub);
      break;
    case "/":
      if (numSub == 0) {
        result = "Can't do that";
      } else {
        result = divide(numIni, numSub);
      }
      break;
    default:
      result = "Null";
  }
  return result;
}
//button display functions
function disNum(val) {
  parseFloat(display.value += val);
}

function disOp(val) {
  // Get last result
  let value = (res.value == '') ? '0' : res.value;
  // Search for valid operator stored previously
  let tmp = value.split('').pop();
  // Is it a valid previous operator?
  op = (['+', '-', '*', '/'].indexOf(tmp) == -1) ? '' : tmp;
  let numIni = parseFloat(value) || 0;
  let numSub = parseFloat(display.value) || 0;

  if(op == '') {
      // No previous operator
      if(res.value == "Can't do that" || res.value == 'Null') {
          res.value = '';
      } else if(display.value != '') {
          // Only if we have a value to show
          res.value = numSub;
      }
      // Don't add = as previous operator
      if(val != '=') {
          res.value += val;
      }
  } else if(display.value != '') {
      // Only do math if we have a value
      res.value = operate(op, numIni, numSub);
      // Don't add = as previous operator
      if(val != '=') {
          res.value += val;
      }
  }
  // Clear display, numIni will be taken from result
  display.value = '';
}

function clr() {
  res.value = '';
  display.value = '';
}
input[type=text] {
  text-align: right;
}
<head>Calc</head>
<div>
  <input type="text" id="result" disabled placeholder="Result"><br>
  <input type="text" id="display">
</div>

<input type="button" value="1" onClick="disNum('1')">
<input type="button" value="2" onClick="disNum('2')">
<input type="button" value="3" onClick="disNum('3')">
<input type="button" value="+" onClick="disOp('+')"><br>
<input type="button" value="4" onClick="disNum('4')">
<input type="button" value="5" onClick="disNum('5')">
<input type="button" value="6" onClick="disNum('6')">
<input type="button" value="-" onClick="disOp('-')"><br>
<input type="button" value="7" onClick="disNum('7')">
<input type="button" value="8" onClick="disNum('8')">
<input type="button" value="9" onClick="disNum('9')">
<input type="button" value="*" onClick="disOp('*')"><br>
<input type="button" value="     0     " onClick="disNum('0')">
<input type="button" value="/" onClick="disOp('/')">
<input type="button" value="=" onClick="disOp('=')"><br>
<input type="button" value="Clear" onClick="clr()">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the wonders of LoopBack querying

Discovering loopback has been an enlightening experience for me. However, as I delve deeper into its functionalities, I've stumbled upon something unexpected. I noticed that when executing queries, such as using the updateAll method, if a parameter i ...

How would the input value change if the clock time changed?

I am working with dynamic inputs that allow me to add and delete rows with inputs. These inputs include material-ui timepickers, which have an icon of a clock next to the input field. When I click on the clock icon, a clock widget appears. However, the val ...

Angular updates location, but browser redirects to incorrect page

I want my application to redirect non-logged in users to a login page. Following advice from a popular source, the app listens for routeChangeStart events like this: $rootScope.$on("$routeChangeStart", function(event, next, current) { if ($rootScope.c ...

The issue of transform scale not functioning properly in conjunction with background clip and gradients in CSS

Looking to transform a div with the transform: scale(-1,1) property while using background-clip: text on the text within it. However, this causes the text to disappear. Here's what I've attempted: .reverse { transform: scale(-1, 1); } .gr ...

Utilize Bootstrap 3 Datepicker version 4 to easily set the date using Moment.js or Date objects

I'm currently utilizing the Within my project, I have a datetime picker labeled as dtpFrom <div class='input-group date ' id='dtpFrom'> <input type='text' class="form-control" /> <span c ...

Preserving state during navigation and router refresh in Next.js version 13

In the component below, we have a Server Component that fetches and renders data. When router.refresh() is called on click, it reruns the page and refetches the data. However, there is an issue with Nextjs preserving the state. Even though the server compo ...

The object's type remains a mystery

While working on implementing jwt authentication in Ionic, React with TypeScript, I faced a typescript error when trying to add a check in my App.tsx file after successful implementation. The error stated: Object is of type 'unknown' Below is ...

Begin your meteor project with a remote MongoDB server on a Windows operating system

Currently tackling a project that requires me to integrate my meteor project with a remote MongoDB server on Windows. I successfully set the environment variable (MONGO_URL="DB LINK") from OSX using terminal commands, but I'm encountering difficulties ...

Refresh the pagination in a jQuery DataTable

I have incorporated DataTable for pagination within my table. The data in the table is loaded through ajax requests, and I am utilizing my custom functions to populate the table manually by interacting with its DOM elements. However, I am facing an issue ...

What is the best way to track and display the window.scrollY value in the console using Next.js

Unfortunately, my ScrollToTop component is not functioning correctly within my app. I have exhausted all possible debugging methods but am still unable to determine why the scrollY value is not being logged as expected. Even after moving the snippet to a ...

Order JSON object based on designated Array

I'm looking to organize a JSON object in a specific order, Here is the current object structure: { "you": 100, "me": 75, "foo": 116, "bar": 15 } I would like to rearrange this object in the following sequence ['me', 'foo', &apos ...

leveraging express.js middleware alongside jwt and express-jwt for secured authentication in express framework

I am encountering an issue while using the express-jwt to create a custom middleware. The error message persists as follows: app.use(expressJwt({ secret: SECRET, algorithms: ['HS256']}).unless({path: ['/login', '/']})); ...

React form events onSubmit and onClick fail to trigger within Zurb Foundation's 'Reveal' modal dialog

Since upgrading from React 16.12.0 to React 17.0.0, I've encountered an issue with my code. Previously, everything worked perfectly fine, but now none of my events seem to be firing (meaning the console.log statement never appears). class MyClass exte ...

Incorrect scope value detected in Angular controller

I recently started learning Angular 1, and I've encountered an issue with my code: var app = angular.module("Football", []); app.factory("competitions", ['$http', function($http) { return $http.get("json/competitions.json") .success(fu ...

Getting a file object with v-file-input in Nuxt.js

For my Nuxt.Js apps, I utilized Vuetify.js as the UI framework. In order to obtain the file object when uploading files, I incorporated the v-file-input component from Vuetify.js and wrote the following code snippet: <template> <div> ...

Utilize a dual-color gradient effect on separate words within the <li> element

I am attempting to display the fizz buzz function in an unordered list, with each word being a different color ('fizz'-- green, 'buzz'--blue) as shown here: https://i.sstatic.net/Yvdal.jpg I have successfully displayed "fizz" and "buz ...

Angular's radio button is set to "checked" on a pre-configured model

Looking for help with customizing alignment of images in a bootstrap/angular template? Check out the code snippet below: <div ng-repeat="a in attributes"> <div class="btn-group" data-toggle="buttons"> <label class="btn btn-white ...

Why is ng-change not functioning properly, especially in conjunction with the Select element?

HTML <select ng-model="selectedName" ng-change="retrieveSelectedClass()" ng-options="(item.name||item) group by item.groupName for item in names" class="code-helper" id="code-helperId"> <option value="">Select Option</op ...

Retrieve new data upon each screen entry

After running a query and rendering items via the UserList component, I use a button in the UserList to run a mutation for deleting an item. The components are linked, so passing the deleteContact function and using refetch() within it ensures that when a ...

Unlocking the Power of Transition: Effortlessly Submitting a Form Post

After the modal finishes fading out, I want my form to be submitted and sent to the email file "refreshform.php". However, currently after the modal fades out, the form does not submit or post anything to the PHP file for sending the email. It simply fades ...