Reputation: 129
I am new to Javascript so this is probably an easy fix but I cannot figure out. I am making a calculator using HTML, CSS and Javascript and I pretty much only know about declaration, if/else statement, for/while loops and some basic elements of CSS and HTML.
here is my javascript code for the calculator.
var firstNum, operator, previousKey, previousNum;
const calculator = document.querySelector('.calculator');
const buttons = calculator.querySelector('.calculator__buttons');
const display = document.querySelector('.calculator__display');
function calculate(n1, operator, n2) {
let result = '';
if(operator === '+'){
result = n1 + n2;
}else if(operator === '-'){
result = n1 - n2;
}else if(operator === '*'){
result = n1 * n2;
}else if(operator === '/'){
result = n1 / n2;
}
return result;
}
buttons.addEventListener('click', function (event) {
const target = event.target;
const action = target.classList[0];
const buttonContent = target.textContent;
if (target.matches('button')) {
let firstNum = 0;
if (action === 'number') {
if (display.textContent > 0 ) {
display.textContent += buttonContent //
}
else {display.textContent = buttonContent}
//display.textContent = buttonContent
console.log('number1 ' + buttonContent + ' button1');
previousKey = 'number';
}
if (action === 'operator') {
console.log('operator1 ' + buttonContent + ' button1');
operator = buttonContent;
firstNum = display.textContent
//console.log(firstNum)
return firstNum
previousKey = 'operator';
}
if (action === 'decimal') {
// console.log('deciaml1');
previousKey = 'decimal';
}
if (action === 'clear') {
display.textContent = '0'
console.log('clear1');
previousKey = 'clear';
}
if (action === 'calculate') {
console.log('caculate1');
display.textContent = calculate(firstNum, operator, display.textContent)
previousKey = 'calculate';
}
}
});
although I set arithmetic operations above as function calculate(n1, operator, n2)
my caculator // here is what it looks like.
result of 5-9 comes out as -59. I will appreciate if I could get some help. thank you in advance.
Upvotes: 0
Views: 652
Reputation: 526
The issue is that you are sending in strings to the calculate function. So you should explicitly convert the string textContent to integer values as such in your code:
if (action === 'calculate') {
console.log('caculate1');
display.textContent = calculate(parseInt(firstNum,10), operator, parseInt(display.textContent,10))
previousKey = 'calculate';
}
Upvotes: 1