I’ve been trying many things to figure out how to solve the two problems I’ve encountered.
The problems are:
- When trying to input “0”, subMath shows 00 - 6
- Equation doesn’t work properly. For example, I entered 1 + 2 and then press “=”, showing 3, but when I try to click on “+” afterward, it add 3 to the subMath, showing 1 + 23. Therefore, after “=” sign, mainMath should be equal to the final answer.
My codepen is: https://codepen.io/kikibres/pen/MEQvqv.
I did several solutions but I couldn’t find the right solution that’ll solve both problems…
My Javascript code is:
$(document).ready(function() {
var mainMath = "0";
var subMath = "0";
var finalset = "";
var nextanswer = "";
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";
if(mainMath.length > 0){
$(".entry").css("font-size", "4em");
}
};
function plusminusScreen() {
mainMath = -1 * mainMath;
finalset = mainMath;
};
function addNumber(keyitem) {
if (mainMath == "0"){
mainMath = keyitem;
finalset = mainMath;
return;
}
mainMath+=keyitem;
/*subMath += "";*/
if(mainMath.length > 8){
$(".entry").css("font-size", "1.5em");
}
};
function addOperator(keyitem){
if(mainMath == "0"){
subMath += "0";
}
if(subMath == "0"){
subMath = "";
}
/*subMath += "";*/
addNumber(keyitem);
subMath += mainMath;
mainMath = "0";
};
function addDecimal(keyitem){
/*if (keyitem == "."){*/
if (mainMath.indexOf(keyitem) === -1){
if(mainMath == "0") {
mainMath = "0" + keyitem;
subMath = "0";
return;
}
} else {
return;
}
/*}*/
addNumber(keyitem);
};
function solveEqual() {
mainMath = eval(subMath+mainMath);
subMath += finalset;
var finalresult = mainMath.toString();
if(finalresult.length > 8){
$(".entry").css("font-size", "1.5em");
}
};
function update(){
$("#answer").html(mainMath);
$("#history").html(subMath);
};
});