feat: rounding, decimal limit, refactors

This commit is contained in:
Mike 2023-10-12 17:17:14 -04:00
parent b923073540
commit 7248f314e1
2 changed files with 28 additions and 11 deletions

View file

@ -16,7 +16,7 @@
align-items: flex-end; align-items: flex-end;
font-family: 'Orbitron', sans-serif; font-family: 'Orbitron', sans-serif;
font-weight: 500; font-weight: 500;
font-size: 4.5em; font-size: 4.3em;
padding: 4px; padding: 4px;
color: #000; color: #000;
} }

View file

@ -7,6 +7,8 @@ const ops = {
operator: undefined, operator: undefined,
numFlag: false, numFlag: false,
onSecondNumber: false, onSecondNumber: false,
stringLength: 8,
periodClicked: false,
updateNum: (num) => { updateNum: (num) => {
if (!this.updateSecondNum){ if (!this.updateSecondNum){
@ -25,6 +27,20 @@ const ops = {
this.numFlag = false; this.numFlag = false;
this.onSecondNumber = false; this.onSecondNumber = false;
display.textContent = "0"; display.textContent = "0";
},
appendNumber: function(num) {
if(!ops.numFlag && ops.checkLength(ops.firstNum)) {
ops.firstNum += num;
updateDisplay(ops.firstNum);
} else if(this.numFlag) {
if (this.checkLength(ops.secondNum)) {
ops.secondNum += num;
updateDisplay(ops.secondNum);
}
}
},
checkLength: function(string) {
return string.length < this.stringLength;
} }
}; };
@ -67,7 +83,8 @@ function handleOperation() {
let first = Number(ops.firstNum); let first = Number(ops.firstNum);
let second = Number(ops.secondNum); let second = Number(ops.secondNum);
let result = operate(first, second, ops.operator); let result = operate(first, second, ops.operator);
result = Math.round(result * (10^3)/(10^3)); // result = Math.round(result * (10^3)/(10^3));
result = result.toPrecision(3);
updateDisplay(result); updateDisplay(result);
ops.firstNum = result; ops.firstNum = result;
ops.secondNum = String(); ops.secondNum = String();
@ -115,15 +132,15 @@ function calculator(event){
if(event.target.dataset.ops === "") { if(event.target.dataset.ops === "") {
handleOperatorClick(event.target.value); handleOperatorClick(event.target.value);
} } else if (event.target.value === '.') {
else if(event.target.dataset.num === "") { if (display.textContent.includes('.')) {
if(!ops.numFlag) { return
ops.firstNum += event.target.value;
updateDisplay(ops.firstNum);
} else { } else {
ops.secondNum += event.target.value; ops.appendNumber(event.target.value)
updateDisplay(ops.secondNum);
} }
} else if(event.target.dataset.num === "") {
ops.appendNumber(event.target.value)
} }
} }