I built a simple Calculator using Javascript, but when I make operations such as 012 + 3 it always returns me 13 and not 15...!
Moreover, in my Calculator when I divide any number with 0 it returns me "Infinity" but I want to return "Error" or "It is not calculable" as string. What can I do in this case?
I spent a lot time in searching solutions here in StackOverflow because I noticed that this problem is very frequently, but I have not found a solution really adaptable for my code.
Here my code:
let output = document.getElementById('output');
let cells = Array.from(document.getElementsByClassName('cell'));
// console.log(cells);
cells.map(cell => {
cell.addEventListener('click', (e) => {
/* console.log('clicked');
console.log(e);
console.log(e.target);
console.log(e.target.innerText); */
switch (e.target.innerText) {
case 'C':
output.innerText = '';
break;
case '=':
// Funzione di gestione degli errori;
try {
output.innerText = eval(output.innerText);
} catch {
output.innerText = 'Error!';
}
break;
default:
output.innerText += e.target.innerText;
}
});
});
<div>
<div class="calculator">
<div id="output"></div>
<div class="buttons">
<button class="cell operator">+</button>
<button class="cell operator">*</button>
<button class="cell operator">/</button>
<button class="cell operator">-</button>
<button class="cell">7</button>
<button class="cell">8</button>
<button class="cell">9</button>
<button class="cell">4</button>
<button class="cell">5</button>
<button class="cell">6</button>
<button class="cell">1</button>
<button class="cell">2</button>
<button class="cell">3</button>
<button class="cell">0</button>
<button class="cell">.</button>
<button class="cell">C</button>
<button class="cell result">=</button>
</div>
</div>
</div>