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()">