JavaScript Calculator

I need someone who has completed his/her JavaScript calculator. I have been stuck with it for days now. I’m having issue with this step 5 * - + 5 = my output is -25 instead of 10. What can I do to fix it ?


const { useState } = React;

function App() {
    const [input, setInput] = useState(''); // Store user input
    const [error, setError] = useState(''); // Error message

    const clearInput = () => {
        setInput(''); // Clear input
        setError(''); // Clear error
    };

    const handleEqual = () => {
        try {
            const evaluated = math.evaluate(input);
            const formattedResult = Number(evaluated).toFixed(4); // Format result to 4 decimal places
            setInput(Number(formattedResult).toString()); // Display the result without trailing zeros
        } catch (error) {
            setError('Invalid expression.');
        }
    };

    const handleInput = (value) => {
        setInput(prev => prev + value); // Append new value
    };

    const handleDecimal = () => {
        const lastNumber = input.split(/[\s+\-*/]/).pop(); // Get the last number
        if (!lastNumber.includes('.')) {
            handleInput('.'); // Append decimal point
        }
    };

    const handleBackspace = () => {
        setInput(prev => prev.slice(0, -1)); // Remove last character from input
    };

    return (
        <div>
            <h2 style={{ border: '2px double green', textAlign: 'center' }}>Simple Calculator</h2>
            <div id="display" style={{ gridColumn: 'span 4' }}>
                {input || '0'} {/* Display current input or 0 */}
            </div>
            <div className="grid">
                <button id="clear" onClick={clearInput}>AC</button>
                <button id="backspace" onClick={handleBackspace}>⌫</button>
                <button id="divide" onClick={() => handleInput(' / ')}>/</button>
                <button id="multiply" onClick={() => handleInput(' * ')}>*</button>
                <button id="seven" onClick={() => handleInput('7')}>7</button>
                <button id="eight" onClick={() => handleInput('8')}>8</button>
                <button id="nine" onClick={() => handleInput('9')}>9</button>
                <button id="subtract" onClick={() => handleInput(' - ')}>-</button>
                <button id="four" onClick={() => handleInput('4')}>4</button>
                <button id="five" onClick={() => handleInput('5')}>5</button>
                <button id="six" onClick={() => handleInput('6')}>6</button>
                <button id="add" onClick={() => handleInput(' + ')}>+</button>
                <button id="one" onClick={() => handleInput('1')}>1</button>
                <button id="two" onClick={() => handleInput('2')}>2</button>
                <button id="three" onClick={() => handleInput('3')}>3</button>
                <button style={{ gridRow: 'span 2'}} id="equals" onClick={handleEqual}>=</button>
                <button style={{ gridColumn: 'span 2'}} id="zero" onClick={() => handleInput('0')}>0</button>
                <button id="decimal" onClick={handleDecimal}>.</button>
            </div>
            {error && <div className="error">{error}</div>}
        </div>
    );
}

ReactDOM.render(<App />, document.getElementById('app'));

how are you handling “operators” typed by user?

happy coding :slight_smile:

I feel the problem is with the logic for handling special cases operations like 5 * - + 5 =
I feel I haven’t reached that milestone. If you can share ideas on how to tackle the problem, I will be appreciative. Every other things works well just this multiple operators that is giving me headache.

i would say try to make use of some “data structure” to keep user pressed “operators” and then decide what to do with them as per instructions

have you tried to do that somehow in your implementation?

happy coding :slight_smile: