I’m building a FreeCodeCamp Calculator. It’s almost finished. I just need to polish up several things. However, the main problem that is bothering me is why did the history area disappear when I press a number…
I tried to code the calculator in a way in which one person presses several numbers, and then presses a operator such as “x”, “+”, etc, the number already entered moves down to the history area. I’ve noticed that when I click on more than one number, the zero disappears. It’s also the same for when I click on a decimal “.”. In the case of the decimals, in first scenario, if I press “.”, the zero didn’t disappear but then I press a number, the zero disappears. In second scenario, if I press a number first, and then press a decimal, the zero disappears. I will list out the scenarios that I’ve experienced.
-
I pressed first number, the zero in the history area didn’t disappear. But when pressing the second and following numbers and decimals, the zero disappears. However, when I presses the operator and the numbers afterward, the history doesn’t disappear. So it means that the zero disappear for the first set before the operator.
-
I pressed the decimal. The zero doesn’t disappear. But when pressing a number or decimal next (I will fix the repeating decimals problem later), the zero disappear. But then after pressing the operator and numbers afterward, the history doesn’t disappear.
How do I fix it?
Here’s my Javascript/JQuery code from Codepen:
$(document).ready(function() {
var mainMath = "0";
var subMath = "0";
var reset = "";
update();
$("button").click(function(){
calculate($(this).attr("value"));
});
function calculate(keyitem) {
switch(keyitem) {
case "clear":
clearScreen();
break;
case "plusminus":
plusminusScreen();
break;
case "%":
percentageScreen();
break;
case "/":
case "*":
case "+":
case "-":
addOperator(keyitem);
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
addNumber(keyitem);
break;
case ".":
addDecimal(keyitem);
break;
case "=":
solveEqual();
break;
}
update();
};
function clearScreen() {
mainMath = "0";
subMath = "0";
};
function plusminusScreen() {
mainMath = -1 * mainMath;
};
function addNumber(keyitem) {
/*if (keyitem == "."){
if(mainMath == "0") {
mainMath = "0" + keyitem;
return;
}
}*/
if (mainMath == "0"){
mainMath = keyitem;
return;
}
if (subMath == "0") {
subMath = "";
}
mainMath+=keyitem;
};
function addOperator(keyitem){
if(mainMath == "0"){
subMath += "0";
}
addNumber(keyitem);
subMath += mainMath;
mainMath = "0";
};
function addDecimal(keyitem){
if (keyitem == "."){
if(mainMath == "0") {
mainMath = "0" + keyitem;
subMath = "0";
return;
}
}
addNumber(keyitem);
};
function solveEqual() {
mainMath = eval(subMath+mainMath);
};
function update(){
$("#answer").html(mainMath);
$("#history").html(subMath);
};
});