-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
112 lines (92 loc) · 2.68 KB
/
script.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
let operator = "";
let display = "";
let currentValue = "";
let previousValue = "";
document.addEventListener("DOMContentLoaded", function(){
let clear = document.querySelector("#clear");
let equal = document.querySelector(".equal");
let decimal = document.querySelector(".decimal");
let numbers = document.querySelectorAll(".number");
let operators = document.querySelectorAll(".operator");
let display = document.querySelector(".calculator-display");
numbers.forEach((number) => number.addEventListener("click", function(e){
handleNumber(e.target.textContent)
display.textContent = currentValue;
}))
operators.forEach((op) => op.addEventListener("click", function(e){
handleOperator(e.target.textContent)
display.textContent = currentValue;
}))
clear.addEventListener("click", function(){
currentValue = "";
operator = "";
display.textContent = currentValue;
})
equal.addEventListener("click", function(){
if (currentValue != "" && previousValue != ""){
operate();
display.textContent = "";
if (previousValue.length <= 10){
display.textContent = previousValue;
}
else {
display.textContent = previousValue.slice(0,10) + "..."
}
}
})
decimal.addEventListener("click", function(){
addDecimal();
})
percent.addEventListener("click", function(){
addPercent();
display.textContent = currentValue;
})
backspace.addEventListener("click", function(){
deleteLast();
display.textContent = 0;
})
})
function handleNumber(num){
if (currentValue.length <=10){
currentValue += num;
}
}
function handleOperator(op){
operator = op;
previousValue = currentValue;
currentValue = "";
}
function operate(){
previousValue = Number(previousValue);
currentValue = Number(currentValue);
if (operator === "+"){
previousValue += currentValue;
}
else if (operator === "-"){
previousValue -= currentValue;
}
else if (operator === "x"){
previousValue *= currentValue;
}
else {
previousValue /= currentValue;
}
previousValue = roundNumber(previousValue);
previousValue = previousValue.toString();
currentValue = previousValue.toString();
}
function roundNumber(num){
return Math.round(num * 1000) / 1000;
}
function addDecimal(){
if (!currentValue.includes(".")){
currentValue += ".";
}
}
function addPercent(){
currentValue = currentValue / 100;
return currentValue
}
function deleteLast(){
currentValue = ""
}