How I Built the CutOnce Calculator Engine
By Scott Brady
Software engineer in Seattle and DIY builder who makes the CutOnce construction calculator.
- cutonce
- swift
- kotlin
- architecture
Someone is going to cut lumber based on the number CutOnce puts on the screen. If 5 ft 3-1/2 in + 7-5/8 in comes back a sixteenth off, a board is wasted. The math behind that answer is a small engine with no UI code in it, written once in Swift and again in Kotlin. The two have to agree on every result. This post walks through how it works.
Every imperial length is an integer
The engine’s central type is Measurement. An imperial measurement holds one number: a 64-bit integer count of 64ths of an inch.
public struct Measurement: Hashable, Codable, Sendable {
public enum Storage: Hashable, Codable, Sendable {
case imperial(sixtyFourths: Int64)
case metric(millimeters: Double)
}
public let storage: Storage
}
One inch is 64. One foot is 768. 5 ft 3-1/2 in is 5 × 768 + 3 × 64 + 32 = 4,064.
A 64th is the finest mark the app supports. Fractions are limited to the denominators 2, 4, 8, 16, 32, and 64, so every length a user can type in feet, inches, and fractions is a whole number of 64ths. Adding and subtracting those lengths is integer addition and subtraction, and the result is exact. Two lengths are equal when their integers are equal.
A Double of inches would also add sixteenths exactly, because halves, quarters, and sixteenths are binary fractions. The integer helps in a different way. A Double can hold values that sit between tape marks, so every comparison and every display would need a rounding step, and each of those is a place for two code paths to round differently. With an integer, a stored imperial length is always a whole number of 64ths.
This also helps with the two-platform setup I described in Native Apps Are Affordable Again. The Kotlin Measurement stores a Long of 64ths. Integer addition gives the same answer in Swift and Kotlin, so there is no floating point rounding for the two apps to disagree on.
A signed 64-bit count of 64ths reaches about 2.3 trillion miles, and the engine still checks for overflow. Addition and subtraction saturate at the limits. A typed length too large to store, such as 9223372036854775807 ft, is rejected with “Measurement too large” by checked arithmetic.
This design was there from the start. The first commit of app code lists “Implement Measurement type stored as 64ths of inch for exact arithmetic” in its message, and the type had a single Int64 field.
Metric is stored separately
Within the first week the type changed from one field to the two-case enum above. Metric values are stored as Double millimeters.
Converting 100 mm to 64ths gives 251.97, which has to round to 252, and 252 64ths is 100.0125 mm. A metric user who types 100 mm should get 100 mm back, so metric lengths stay in millimeters and never pass through 64ths unless they are mixed with an imperial value.
When the two systems are mixed, the left operand decides the result. 1 ft + 100 mm is an imperial result of 1,020 64ths, which is 1 ft 3-15/16 in. 100 mm + 1 ft is a metric result of 404.8 mm, give or take the last bit of the Double.
Parsing: lexer, parser, tree
Input text goes through three stages, with no regular expressions.
The lexer turns characters into tokens: integers, decimals, units, operators, and parentheses. It accepts ' and ", straight or curly, as well as ft, feet, foot, in, inch, and inches.
The parser turns tokens into a tree using precedence climbing, so multiplication and division bind tighter than addition and subtraction. Two characters are ambiguous in construction notation, and the parser resolves each with a simple rule:
/is always the fraction bar. Division is÷, a separate token.-is part of a mixed number only when it touches the previous token with no space.3-1/2 inis three and a half inches.3 in - 1/2 inis a subtraction, and the answer is 2-1/2 in.
A fraction with an unsupported denominator, such as 1/3, is a parse error with a message. Nesting is capped at 128 levels so a long run of parentheses cannot overflow the stack.
The tree is one recursive enum:
public indirect enum MeasurementExpression: Equatable, Sendable {
case measurement(Measurement)
case scalar(Double)
case area(Area)
case volume(Volume)
case binaryOp(lhs: MeasurementExpression, op: BinaryOperator, rhs: MeasurementExpression)
case negate(MeasurementExpression)
case group(MeasurementExpression)
}
Evaluation tracks dimensions
Evaluating the tree returns a length, a plain number, an area, a volume, or an error. The evaluator checks the kinds of both operands:
| Expression | Result |
|---|---|
| length + length | length |
| length × number | length |
| length × length | area |
| area × length | volume |
| volume ÷ area | length |
| length ÷ length | number |
| length + area | error |
The first version got this wrong. It treated the right side of a multiplication as a plain number, so 2 ft × 2 ft returned a length. The fix landed a few days later, and 2 ft × 2 ft has been 4 sq ft since.
Areas and volumes are stored as Double square and cubic inches. The exact-integer rule applies to lengths.
The table describes the expression evaluator. The keypad engine in the next section supports a subset: it has no pending operation for a volume, so pressing an operator after a volume result does nothing. That gap is tracked as an open ticket.
The keypad is a state machine
A calculator does not receive a finished string. It receives one key at a time. CalculatorEngine wraps the parser in a state machine with one entry point:
public func input(_ key: CalculatorKey)
CalculatorKey is an enum of every key: digits, units, operators, equals, clear, memory, and so on. The engine keeps a text buffer of what is being typed. When an operator or equals arrives, it parses the buffer into a result, stores the operator and left operand as a pending operation, and waits for the right operand.
All of that lives in one Codable struct, CalculatorState, with no reference to any view. The Swift package it belongs to imports only Foundation. A test can press keys and compare state without launching the app, and the app can save and restore the whole calculator by encoding one value.
Rounding happens at the display
The engine keeps full 64th precision and rounds only when formatting for the screen, at a resolution the user picks. The default is 1/16.
Rounding a fraction can carry. At 1/16 resolution, 11-31/32 in rounds up to 12 inches, which has to display as 1 ft and not as 0 ft 12 in. The formatter handles the carry from fraction to inches to feet.
Rounding parts independently can also break a sum. Take two pieces of 3/32 in each. The total is exactly 3/16 in. At 1/16 resolution each piece rounds to 1/8 in, and 1/8 + 1/8 is 1/4, which is 1/16 more than the total printed next to them. This showed up on the rafter calculator, where rafter length plus tail length did not always equal the total rafter length on the cut sheet. The fix was a reconcile function: round the total, round one part, and derive the other part by subtraction so the three printed numbers always add up.
Taking floating point out of the input path
The integer storage was exact from day one, but a value could still pass through a Double on its way in. Typing a decimal such as 4.5 ft parsed the number as a Double, multiplied, and rounded to 64ths.
For ordinary inputs that gives the right answer. A plan review later found one where it does not: 1.007812499999999999 inches. Times 64, that is 64.499999999999999936, which rounds to 64. A Double cannot hold that many digits, so it reads the literal as exactly 1.0078125, which is 64.5 and rounds to 65. The result was off by one 64th.
That input is unlikely on a jobsite. The project rule is that imperial values never go through floating point, though, and every calculator’s keypad and paste path used this parser. I chose to fix it once, in the shared parser. Decimal literals are now kept as their digits and converted to 64ths with integer math, digit by digit, with overflow checks.
A follow-up did the same for multiplication and division by a typed number. Before it, 1 in × 1.007812499999999999 gave 65/64, and the same two operands in the other order gave 64/64. 1 in ÷ 42.666666666666667 gave 2/64, where the exact quotient rounds to 1/64. The engine now scales the 64ths by the typed digits in 128-bit integer math and rounds once at the end. Both operand orders give the same answer, and a result too large to store is an error on the display. Before the fix it was silently clamped to the largest storable value.
Three implementations
The Android engine was ported from the Swift one over two days, in the same order the Swift one was built: models, then the lexer and parser, then CalculatorEngine. Today the parsing, measurement, and engine files are about 4,200 lines of Swift and about 3,800 lines of Kotlin.
The website’s feet and inches calculator is a TypeScript port of the same arithmetic, and it also works in 64ths. A script in the site’s prebuild step checks the ports against vectors copied from named app tests, and a mismatch fails the build.
Tests
The first commit shipped with 74 unit tests. The same day, a JSON file of test cases covering the four operations, input formats, boundaries, and errors was turned into Swift tests. Several were committed disabled because the calculator failed them, and the rest of that day’s commits fixed the engine until they could be turned on: scalar multiplication and division, non-binary denominators, negation.
The suite has grown the same way since: a failing case first, then the fix. The Swift package’s test directory now has 8,382 @Test functions. About 650 of them are in the test files for the lexer, parser, measurement, fraction, and engine.
Across the whole product there are over 12,000 automated tests, and 1,714 of them are shared vectors that run identically on iOS and Android. Those shared vectors cover the specialized calculators such as stairs, rafters, and tile. The main calculator has none. It is covered by each platform’s own suite, and the How we verify accuracy page says so in its per-calculator breakdown.
Summary
The engine is a value type that stores imperial lengths as integer 64ths, a lexer and parser that understand construction notation, an evaluator that tracks length, area, and volume, and a key-driven state machine around them. The integer storage was the first decision and it has held up. Most of the work since has been at the edges: where values come in as text, and where they go out as rounded fractions.