-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
79 lines (70 loc) · 1.83 KB
/
Copy pathscript.js
File metadata and controls
79 lines (70 loc) · 1.83 KB
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
const display = document.getElementById('display');
const buttons = document.querySelectorAll('.btn');
let currentInput = '';
let operator = '';
let firstNumber = '';
let secondNumber = '';
let hasDecimal = false;
buttons.forEach(button => {
button.addEventListener('click', () => {
const value = button.getAttribute('data-value');
if (button.id === 'clear') {
clearCalculator();
} else if (button.id === 'equals') {
calculateResult();
} else if (button.classList.contains('operator')) {
setOperator(value);
} else {
addInput(value);
}
});
});
function clearCalculator() {
currentInput = '';
operator = '';
firstNumber = '';
secondNumber = '';
hasDecimal = false;
display.textContent = '0';
}
function addInput(value) {
if (value === '.' && hasDecimal) return; // Prevent adding more than one decimal point.
if (value === '.') {
hasDecimal = true;
}
currentInput += value;
display.textContent = currentInput;
}
function setOperator(value) {
if (currentInput) {
firstNumber = currentInput;
operator = value;
currentInput = '';
hasDecimal = false; // Reset decimal flag when moving to the next number
}
}
function calculateResult() {
if (firstNumber && operator && currentInput) {
secondNumber = currentInput;
const result = calculate(Number(firstNumber), Number(secondNumber), operator);
display.textContent = result;
currentInput = result.toString();
firstNumber = '';
operator = '';
hasDecimal = result.toString().includes('.'); // Track if the result has a decimal
}
}
function calculate(a, b, op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return b !== 0 ? a / b : 'Error'; // Division by zero check
default:
return 0;
}
}