Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed point functionality in Basic Calculator #820

Merged
merged 8 commits into from
May 25, 2024
2 changes: 1 addition & 1 deletion Calculators/Basic-Calculator/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
<span class="num" onclick="calc.txt.value += '6' "><i>6</i></span>
<span class="num" onclick="calc.txt.value += 'Math.sqrt(' "><i>√</i></span>
<span class="num" onclick="calc.txt.value += '%' "><i>%</i></span>
<span class="num" onclick="calc.txt.value += '.' "><i>.</i></span>
<span class="num point" onclick="point()"><i>.</i></span>
<span class="num" onclick="calc.txt.value += '1' "><i>1</i></span>
<span class="num" onclick="calc.txt.value += '2' "><i>2</i></span>
<span class="num" onclick="calc.txt.value += '3' "><i>3</i></span>
Expand Down
38 changes: 37 additions & 1 deletion Calculators/Basic-Calculator/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,15 @@ let display = document.getElementById("display");
document.addEventListener("keydown", function (event) {
const validKeys = /^[0-9.\+\-\*\/\(\)\^\%\{\}\[\]&]$/;
if (validKeys.test(event.key)) {
document.getElementById("display").value += event.key;
if (event.key === ".") {
console.log(event.key)
event.preventDefault();
point();
}
else {
event.preventDefault();
document.getElementById("display").value += event.key;
}
} else if (event.key === "Enter") {
event.preventDefault();
calculate();
Expand Down Expand Up @@ -46,3 +54,31 @@ function clearOne() {
let currentValue = calc.txt.value;
calc.txt.value = currentValue.slice(0, -1);
}

function point() {
let currentValue = calc.txt.value;
if (currentValue == "") {
calc.txt.value = '0' + '.';
}
else {

if (currentValue.charAt(currentValue.length - 1) == "." || currentValue.charAt(currentValue.length - 1) == "(") {
calc.txt.value = calc.txt.value + '0' + '.';
return;
}
if (currentValue.charAt(currentValue.length - 1) == "+" ||
currentValue.charAt(currentValue.length - 1) == "*" ||
currentValue.charAt(currentValue.length - 1) == "-" ||
currentValue.charAt(currentValue.length - 1) == "/" ||
currentValue.charAt(currentValue.length - 1) == "%" ||
currentValue.charAt(currentValue.length - 1) == "√" ||
currentValue.charAt(currentValue.length - 1) == "^") {
calc.txt.value = calc.txt.value + '0' + '.';
return;
}
else {
calc.txt.value = calc.txt.value + ".";
return;
}
}
};