mercredi 8 juillet 2020

I cannot produce an error message with division when dividing by 0 (Javascript Calculator)

To preface this, I'm a beginner who's attempting to create a calculator in Javascript. I currently have a switch statement containing math operators. My issue is that in the switch statement, I want to include an error message (string) where division is concerned when trying to divide by 0; however, no matter what I do, I always get infinity up in the calculator's 'display.'

Any amount of help is greatly appreciated, even if it means me having to re-do this whole thing. Here is a snippet of the function(s) doing the actual calculation (though it is in a class, I will edit in the whole block of code if requested).

selectedOperation(operation) {
        if (this.currentDisplay === '') return;
        if (this.prevDisplay !== '') {
            this.calculate();
        }
        this.operation = operation;
        this.prevDisplay = this.currentDisplay;
        this.currentDisplay = '';
}

calculate() {
        let calculation;
        const previousNum = parseFloat(this.prevDisplay);
        const currentNum = parseFloat(this.currentDisplay);
        if (isNaN(previousNum) || isNaN(currentNum)) return;
        
        switch (this.operation) {
            case '+' : 
            calculation = previousNum + currentNum
            break;
        case '-' : 
            calculation = previousNum - currentNum
            break;
        case 'x' : 
            calculation = previousNum * currentNum
            break;
        case '÷' : 
            calculation = previousNum / currentNum
            if (currentNum === 0) return "error";
            break;
        default:
            return;
        }

        this.currentDisplay = calculation;
        this.operation = undefined;
        this.prevDisplay = '';
}

Aucun commentaire:

Enregistrer un commentaire