Dev.to WebDev 🛠 Dev 👁 0 📖 6 min read

Deterministic Imperial Feet-and-Inches Dimension Parsing and CAD Geometry Math in TypeScript

Most web developers only deal with metric pixels or CSS percentages until they build a residential floor plan editor for the United States. The moment US homeowners, remodelers, and framers start entering room sizes, eve

Most web developers only deal with metric pixels or CSS percentages until they build a residential floor plan editor for the United States. The moment US homeowners, remodelers, and framers start entering room sizes, every input arrives in mixed imperial syntax: 14'-6 1/2", 14ft 6.5in, 14'6", 174.5", or 14.5'.

If a browser CAD engine handles those values casually with floating-point approximations or loose regular expressions, small errors compound across a 40-foot structure. Exterior dimension chains stop summing to the overall footprint, polygon corners drift off orthogonal snap lines by 0.0000001 inches, and printed 1/4" = 1'-0" sheets come off the plotter slightly out of scale.

While building the browser-based 2D/3D drafting studio at PlanCaliber, we standardized every wall, door opening, room polygon, and printed drawing sheet on a deterministic imperial geometry layer in TypeScript. Here is the exact architecture and math behind it.

1. Pick One Canonical Storage Unit: Exact Fractional Inches

The single worst mistake in a residential drafting engine is storing coordinates in CSS pixels or decimal feet.

  • CSS pixels couple geometry to viewport zoom and DPI.
  • Decimal feet turn common US framing increments into repeating decimals (1/12 = 0.083333..., 7" = 0.583333..., 3 1/2" stud width = 0.291666...).

By contrast, inches map cleanly to US lumber dimensions, drywall sheets (48" x 96"), door rough openings (32", 36"), kitchen cabinet modules (24" base depth, 12" wall depth), and AutoCAD R12 $INSUNITS = 1 (inches).

To avoid binary floating-point drift on fractional tape-measure increments (1/2", 1/4", 1/8", 1/16"), every parsed length snaps cleanly to integer sixteenths of an inch (1/16" = 0.0625"), which has an exact representation in IEEE-754 double precision because 16 = 2^4.

export const SIXTEENTHS_PER_INCH = 16;

export function snapToSixteenth(inches: number): number {
  return Math.round(inches * SIXTEENTHS_PER_INCH) / SIXTEENTHS_PER_INCH;
}

export function formatFeetInches(rawInches: number, precision: 2 | 4 | 8 | 16 = 16): string {
  const sign = rawInches < 0 ? '-' : '';
  const totalUnits = Math.round(Math.abs(rawInches) * precision);
  const wholeInches = Math.floor(totalUnits / precision);
  const fracUnits = totalUnits % precision;

  const feet = Math.floor(wholeInches / 12);
  const inches = wholeInches % 12;

  if (fracUnits === 0) {
    return `${sign}${feet}'-${inches}"`;
  }

  const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));
  const d = gcd(fracUnits, precision);
  const num = fracUnits / d;
  const den = precision / d;

  return `${sign}${feet}'-${inches} ${num}/${den}"`;
}

Notice two subtle safeguards in formatFeetInches:

  1. We round before splitting feet and inches. Without that step, 11.99" can mistakenly format as 0'-12" instead of 1'-0".
  2. Reducing the fraction with gcd guarantees 8/16" always prints as 1/2" and 4/16" prints as 1/4".

2. Parsing Real-World US Imperial User Input Without Ambiguity

Users rarely type textbook drafting notation. On a job site or couch, they type 12' 6", 12'-6 1/2", 12ft 6in, 12.5, or 36". A strict deterministic parser handles every variant predictably and rejects malformed strings instead of silently returning NaN:

const IMPERIAL_REGEX =
  /^\s*(?:(?<feet>\d+(?:\.\d+)?)\s*(?:'|ft|feet)\s*-?\s*)?(?:(?<inches>\d+(?:\.\d+)?)\s*(?:(?<num>\d+)\s*\/\s*(?<den>\d+))?\s*(?:"|in|inches)?)?\s*$/i;

export function parseImperialToInches(input: string, defaultUnit: 'ft' | 'in' = 'ft'): number | null {
  const trimmed = input.trim();
  if (!trimmed) return null;

  // Bare number with no unit symbol uses the field's explicit default unit
  if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
    const val = Number(trimmed);
    return snapToSixteenth(defaultUnit === 'ft' ? val * 12 : val);
  }

  // Standalone fraction like "3/4\"" or "1/2"
  const fracOnly = trimmed.match(/^(\d+)\s*\/\s*(\d+)\s*(?:"|in|inches)?$/i);
  if (fracOnly) {
    const num = Number(fracOnly[1]);
    const den = Number(fracOnly[2]);
    if (den === 0) return null;
    return snapToSixteenth(num / den);
  }

  const m = trimmed.match(IMPERIAL_REGEX);
  if (!m?.groups) return null;

  const { feet, inches, num, den } = m.groups;
  if (!feet && !inches) return null;

  let total = 0;
  if (feet) total += Number(feet) * 12;
  if (inches) total += Number(inches);
  if (num && den) {
    const d = Number(den);
    if (d === 0) return null;
    total += Number(num) / d;
  }

  return Number.isFinite(total) ? snapToSixteenth(total) : null;
}

Test cases verify every edge:

  • parseImperialToInches("14'-6 1/2\"") -> 174.5
  • parseImperialToInches("24ft") -> 288
  • parseImperialToInches("36\"") -> 36
  • parseImperialToInches("12.5", "ft") -> 150
  • parseImperialToInches("12'-0\"") -> 144

3. Exact Polygon Square Footage With the Shoelace Formula

Residential rooms are frequently L-shaped (primary suites with entry alcoves, open kitchen/great rooms, or garages wrapped around mudrooms). Computing square footage from a bounding box overstates area on every non-rectangular room.

Given an ordered closed loop of room vertices (x_i, y_i) stored in exact inches, the Gauss shoelace formula returns exact square footage in O(n) time:

export interface Point2D {
  x: number; // inches
  y: number; // inches
}

export function polygonAreaSqFt(vertices: readonly Point2D[]): number {
  const n = vertices.length;
  if (n < 3) return 0;

  let doubleSqInches = 0;
  for (let i = 0; i < n; i++) {
    const a = vertices[i];
    const b = vertices[(i + 1) % n];
    doubleSqInches += a.x * b.y - b.x * a.y;
  }

  const sqInches = Math.abs(doubleSqInches) / 2;
  return Math.round((sqInches / 144) * 100) / 100;
}

Consider an L-shaped studio wing measuring 24'-0" (288") across the bottom, 14'-6 1/2" (174.5") along the left wall, stepping inward 12'-0" (144") and down 6'-6 1/2" (78.5") to an 8'-0" (96") right wall:

  • Left wing: 12.0 ft * 14.541667 ft = 174.50 sq ft
  • Right wing: 12.0 ft * 8.0 ft = 96.00 sq ft
  • Shoelace total: 270.50 sq ft (exact to the hundredth of a square foot, invariant to clockwise vs counter-clockwise vertex order).

4. Wall Centerline vs Clear Interior Dimensions

A common source of field-framing headaches is conflating exterior footprint dimensions with clear interior room dimensions:

  • Standard US exterior wood-frame walls are 2x6 (5.5" stud + 0.5" sheathing + 0.5" drywall = 6.5" nominal, or 6" in preliminary space planning).
  • Standard interior partition walls are 2x4 (3.5" stud + two 0.5" drywall faces = 4.5").

When a floor plan stores walls by centerline coordinates (x1, y1) -> (x2, y2) plus explicit thicknessInches:

  • Gross Living Area (GLA) follows exterior wall outer faces (ANSI Z765 convention for residential footprint measurements).
  • Clear Interior Room Width subtracts half the thickness of each bounding wall (clearWidth = centerlineSpan - (tLeft / 2) - (tRight / 2)). That matters immediately when checking whether a 76" x 80" US King mattress or a 36" kitchen walkway actually fits inside real drywall faces rather than zero-thickness diagram lines.

5. Exact 1/4" = 1'-0" Print Scale Projection to PDF Points

When exporting a browser plan to a print-ready vector PDF (where 1 PDF point = 1/72 inch), keeping the scale exact requires one clean ratio:

  • At 1/4" = 1'-0" (scale factor 1:48), every 12 real-world inches equals 0.25 paper inches, so 1 real-world inch equals 1 / 48 paper inches.
  • Converting paper inches to PDF points (72 pt / in):
export type ImperialScale = '1/4' | '3/16' | '1/8';

export function scaleRatio(scale: ImperialScale): number {
  switch (scale) {
    case '1/4':
      return 1 / 48; // 0.25 in per 12 in
    case '3/16':
      return 3 / 192; // 0.1875 in per 12 in
    case '1/8':
      return 1 / 96; // 0.125 in per 12 in
  }
}

export function realInchesToPdfPoints(realInches: number, scale: ImperialScale = '1/4'): number {
  return realInches * scaleRatio(scale) * 72;
}

Let's verify on a concrete number:

  • For 14'-6 1/2" (174.50 real inches) at 1/4" = 1'-0":
    • Paper length = 174.50 / 48 = 3.6354 in
    • Vector PDF length = 174.50 * (72 / 48) = 174.50 * 1.5 = 261.75 pt (completely exact, zero rounding residue!).
  • Notice that 72 / 48 = 1.5 exactly, and 72 / 96 = 0.75 exactly. Because 72 is divisible by 24, standard US drafting scales (1/4", 1/8", 1/2", 3/8") yield clean finite PDF point multipliers with zero cumulative scaling error across an entire 11" x 17" Tabloid or 24" x 36" ARCH D sheet!

You can check paper fit across Letter, Tabloid (11"x17"), ARCH C, and ARCH D live with our free Floor Plan Scale Calculator, or inspect how these calculations drive full 2D/3D residential layouts on templates like our 1,500 Sq Ft 3-Bed Ranch and 40'x80' Barndominium + RV Shop.

6. Putting It Together in Production

In PlanCaliber, the entire 2D canvas, 3D extruded preview, framing takeoff CSV, AutoCAD R12 .DXF exporter ($INSUNITS = 1), and scaled vector PDF generator read from this single inches-based geometry core:

  • Free Studio Draft ($0): Full 2D/3D drafting, 40 US templates, 20 building-code calculators, 2 AI sketch/text scans/day, and instant watermarked proof PNG exports.
  • Print Pass ($9 one-time): Unwatermarked 2-sheet vector PDF (A-101 + M-101), 2400px PNG, SVG, custom title block, and permanent edits.
  • Full CAD Pack ($19 one-time, or $49 5-Plan Pack): Full 5-sheet 1/4" = 1'-0" PDF set (A-101, A-102, E-101, A-201, M-101), 8-layer AutoCAD R12 .DXF, 3D .OBJ/.MTL, and Framing & Drywall .CSV takeoff.

Note: PlanCaliber generates preliminary space-planning drawings and material estimates only. Always verify field measurements, structural engineering, and local municipal code requirements with licensed local professionals before construction.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.