Implementing Calculator in Mobile App
Calculator looks trivial—until you support operation chains, handle floating-point precision loss, and avoid QA bug "0.1 + 0.2 = 0.30000000000000004".
Calculation Logic and Precision
Most important decision—where to calculate. Built-in types Double / Float use IEEE 754 floating-point with known limitations. For financial calculator or accounting app this is unacceptable.
On iOS correct path—NSDecimalNumber or Decimal from Foundation. Decimal(string: "0.1") + Decimal(string: "0.2") gives exactly 0.3. For complex expressions—NSExpression or custom parser with tokenizer. On Android—java.math.BigDecimal with explicit MathContext.DECIMAL128 and RoundingMode.HALF_UP on division. Dividing BigDecimal without MathContext—ArithmeticException on non-terminating decimal (e.g., 1/3).
For parsing expressions like 2 + 3 * 4 with operator precedence—Dijkstra's shunting-yard algorithm. Implemented in ~100 lines, no external dependencies, covered by unit tests for every edge case. Alternative—exp4j library on Android or MathParser.org-mXparser for cross-platform.
UI and State
Architecturally calculator is finite state machine. States: idle, enteringFirstOperand, operatorEntered, enteringSecondOperand, resultDisplayed, error. Transitions between states on each button press. Storing just currentInput: String and operator: String—path to bugs with series of operator presses or = without second operand.
On iOS—ViewModel with @Published properties or Combine. On Android—ViewModel + StateFlow. In Flutter—BLoC or ChangeNotifier. Calculation logic—in separate use case / service, covered by tests independent of UI.
Keyboard: LazyVGrid in SwiftUI or GridLayout in Compose simplest. Only nuance—0 button usually takes double width, requiring GridItem with span or separate HStack for last row.
Typical Edge Cases
- Multiple decimal points in one number—need check before adding symbol
- Division by zero—not crash, display "Error" with restart option
- Overflow on very large numbers—
DecimalandBigDecimaldon't overflow likeDouble, but result can become unreadable; need limit on display digit count - Operator chain:
5 + 3 * 2—calculate left-to-right (like simple calculators) or with multiplication priority? Depends on spec
Timeline: basic calculator with four operations—1 day. Scientific with operator precedence, calculation history and BigDecimal—2–3 days.







