class CalculatorLogic { String _display = '0'; double _firstOperand = 0; String _operator = ''; bool _waitingForSecondOperand = false; String get display => _display; void inputDigit(String digit) { if (_waitingForSecondOperand) { _display = digit; _waitingForSecondOperand = false; } else { _display = _display == '0' ? digit : _display + digit; } } void inputDecimal() { if (_waitingForSecondOperand) { _display = '0.'; _waitingForSecondOperand = false; return; } if (!_display.contains('.')) { _display += '.'; } } void inputOperator(String op) { final current = double.parse(_display); if (_operator.isNotEmpty && !_waitingForSecondOperand) { _firstOperand = _calculate(_firstOperand, current, _operator); _display = _formatResult(_firstOperand); } else { _firstOperand = current; } _operator = op; _waitingForSecondOperand = true; } void calculate() { if (_operator.isEmpty) return; final secondOperand = double.parse(_display); final result = _calculate(_firstOperand, secondOperand, _operator); _display = _formatResult(result); _firstOperand = result; _operator = ''; _waitingForSecondOperand = true; } void clear() { _display = '0'; _firstOperand = 0; _operator = ''; _waitingForSecondOperand = false; } void toggleSign() { final value = double.parse(_display); _display = _formatResult(-value); } void percent() { final value = double.parse(_display); _display = _formatResult(value / 100); } double _calculate(double a, double b, String op) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': if (b == 0) return double.infinity; return a / b; default: return b; } } String _formatResult(double value) { if (value.isInfinite || value.isNaN) { return value.toString(); } if (value == value.toInt().toDouble()) { return value.toInt().toString(); } return value.toString(); } }