-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.js
91 lines (81 loc) · 3.02 KB
/
scripts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
let displayTxtField = document.getElementById("resultDisplay");
let fPointBtn = document.getElementById("fPoint");
const buttonsList = document.querySelectorAll("input[type=button]");
let displayValue = '';
let firstValue = 0;
let operator = '';
for(button of buttonsList){
button.addEventListener('click', (e) => {
let buttonText = e.target.value;
if(buttonText >= 0 || buttonText <= 9 || buttonText == '.'){
if (buttonText == '.' ) {
fPointBtn.disabled = true;
}
displayValue += buttonText;
displayTxtField.value = displayValue;
}else{
if(buttonText === '+') {
operator = '+';
firstValue = displayValue;
displayValue = '';
fPointBtn.disabled = false;
}else if(buttonText === '-') {
operator = '-';
firstValue = displayValue;
displayValue = '';
fPointBtn.disabled = false;
}else if(buttonText === 'x') {
operator = 'x';
firstValue = displayValue;
displayValue = '';
fPointBtn.disabled = false;
}else if(buttonText === '/') {
operator = '/';
firstValue = displayValue;
displayValue = '';
fPointBtn.disabled = false;
console.log("firstValue: " + firstValue);
console.log("displayValue: " + displayValue);
}else if(buttonText === '=') {
if (firstValue === '' || displayValue === '') {
displayTxtField.value = 0;
}else{
if(operator == '/' && displayValue == 0){
displayTxtField.value = "Cannot divide by 0";
}else{
displayValue = operate(operator, parseFloat(firstValue), parseFloat(displayValue));
displayTxtField.value = displayValue ;
console.log("Total: " + displayValue);
}
}
}else if(buttonText === 'C') {
clearDisplay();
}
}
})
}
function backSpace(){
displayValue = displayValue.substring(0, displayValue.length-1)
displayTxtField.value = displayTxtField.value.substring(0, displayTxtField.value.length-1)
}
function clearDisplay(){
displayValue = '';
firstValue = 0;
operator = '';
displayTxtField.value = displayValue;
fPointBtn.disabled = false;
}
function operate(operator, num1, num2){
let divideOpe = 0;
if (operator === '+'){
return num1 + num2;
}else if (operator === '-'){
return num1 - num2;
}else if (operator === 'x'){
return num1 * num2;
}else{
divideOpe = num1 / num2
return divideOpe.toFixed(6);
}
}
window.onload = clearDisplay();