-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
66 lines (54 loc) · 1.36 KB
/
script.js
File metadata and controls
66 lines (54 loc) · 1.36 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
/**
* Calculator Logic v3
* Handles mathematical operations, UI updates, and floating-point precision fixes.
*
* @author Claudio Borromei
* @version 3.0
*/
let input = document.getElementById('inputBox');
let button = document.querySelectorAll('button');
let string = "";
let isResultDisplayed = false;
const operators = ['+', '-', '*', '/', '%'];
let arrayButtons = Array.from(button);
arrayButtons.forEach(button => {
button.addEventListener('click', (e) => {
let btnText = e.target.innerHTML;
if (btnText == '=') {
let result = eval(string);
// Fix floating-point imprecision (e.g., 0.1 + 0.2) by rounding to 10 decimal places
string = Number(result.toFixed(10)).toString();
input.value = string;
isResultDisplayed = true;
}
else if (btnText == 'AC') {
string = "";
input.value = string;
}
else if (btnText == 'C') {
string = string.substring(0, string.length - 1);
input.value = string;
}
else if (operators.includes(btnText)) {
const lastChar = string.slice(-1);
if (operators.includes(lastChar)) {
string = string.slice(0, -1) + btnText;
}
else {
string += btnText;
}
input.value = string;
isResultDisplayed = false;
}
else {
if (isResultDisplayed == true) {
string = btnText;
}
else {
string += btnText;
}
input.value = string;
isResultDisplayed = false;
}
})
})