Eliminating Floating-Point & Carry-Over Bugs in Browser-Local Engineering Converters with TypeScript
Unit and engineering converters look trivial on paper—multiply by a constant, format a string, render the result. Then real inputs hit IEEE 754 floating-point arithmetic and loose JavaScript type coercion: Multiply 0.1
Unit and engineering converters look trivial on paper—multiply by a constant, format a string, render the result. Then real inputs hit IEEE 754 floating-point arithmetic and loose JavaScript type coercion:
- Multiply
0.1feet by12inches in JavaScript and you get1.2000000000000002. - Round
totalInchesto 4 decimal places before snapping to1/64"carpentry fractions, and exact midpoints like1/128"(0.0078125") can tip across the wrong rounding boundary. - Forget carry-over normalization, and
1.999feet renders as1' 11-16/16"instead of2' 0". - Let
Number("")silently evaluate to0in an electrical calculator, and clearing an input produces false zero-current readings or division-by-zero errors downstream. - Ignore
-0sign semantics, and-0.000001feet prints as-0' 0".
When calculations run purely client-side in TypeScript, mathematical invariants and input boundary parsing cannot be afterthoughts. Below are the concrete patterns—and Vitest edge-case suites—we use to keep surveying and electrical engineering calculators deterministic.
1. Separate Intermediate Precision From Display Rounding
In civil engineering and land surveying, elevation stakes are recorded in decimal feet (tenths and hundredths of a foot), where 0.1 ft = 1.2 in. Carpenters and field crews, however, read imperial tape measures in feet, inches, and power-of-two fractions (1/8", 1/16", 1/32", 1/64").
A common implementation bug is rounding totalInches to display precision (such as 4 decimal places) before computing the fractional remainder. At 1/64" (0.015625") or 1/128" (0.0078125"), truncating or rounding early changes whether a midpoint rounds up or down.
Instead, separate high-precision intermediate rounding (10 decimals—enough to cancel binary noise like 0.1 * 12 = 1.2000000000000002 without distorting 1/64" midpoints) from display rounding (4 decimals):
export const INCHES_PER_FOOT = 12;
export type PrecisionDenominator = 8 | 16 | 32 | 64;
function normalizeZero(val: number): number {
return val === 0 ? 0 : val;
}
export const roundDecimals = (val: number, decimals = 4): number => {
if (!Number.isFinite(val)) return 0;
const safeDecimals =
Number.isInteger(decimals) && decimals >= 0 && decimals <= 12 ? decimals : 4;
const factor = 10 ** safeDecimals;
const rounded = Math.round((val + Number.EPSILON * Math.sign(val)) * factor) / factor;
return normalizeZero(rounded);
};
Two details matter here:
-
Number.isFinite(val)turnsNaNorInfinityinto0at the helper boundary rather than propagatingNaNinto DOM text. -
normalizeZerocatches JavaScript's-0(for example,Math.round(-0.000001 * 10000) / 10000 === -0), which otherwise passesval === 0yet breaksObject.is(val, 0)assertions and sign formatting.
Carry-Over Normalization, -0' 0" Guards, and Tolerance Deviation
Once you have exactTotalInches, decompose it into whole inches and a fractional remainder. The key trap happens when Math.round(fractionRemainder * safePrecision) equals safePrecision—for instance, 11 + 15.9/16 inches rounding to 11-16/16". That fraction must carry into whole inches, and if whole inches reaches 12, it must carry into feet:
const exactTotalInches = roundDecimals(absFt * INCHES_PER_FOOT, 10);
const totalDecimalInches = roundDecimals(exactTotalInches, 4);
const wholeTotalInches = Math.floor(exactTotalInches);
const fractionRemainder = exactTotalInches - wholeTotalInches;
const rawNumerator = Math.round(fractionRemainder * safePrecision);
let carryInches = 0;
let fractionNumerator = 0;
let fractionDenominator = safePrecision;
if (rawNumerator >= safePrecision) {
carryInches = 1;
} else if (rawNumerator > 0) {
const divisor = gcd(rawNumerator, safePrecision);
fractionNumerator = rawNumerator / divisor;
fractionDenominator = safePrecision / divisor;
}
const totalNominalInches = wholeTotalInches + carryInches;
const feet = Math.floor(totalNominalInches / INCHES_PER_FOOT);
const inches = totalNominalInches % INCHES_PER_FOOT;
After carry-over normalization, two more guards prevent subtle UI mismatches:
-
Effective-zero sign guard: Inputs like
-0.000001 ftstart negative (safeFeet < 0) but round to0inches and0fraction ticks. CheckisEffectiveZero = totalDecimalInches === 0 && totalNominalInches === 0 && !hasFraction, and computeisNegative = safeFeet < 0 && !isEffectiveZeroso the formatter never emits-0' 0". -
Residual deviation (
heavyvs.light): Because0.7 ft = 8.4", snapping to1/16"gives8-3/8"(8.375"), leaving+0.025"(~1/40"heavy). ComputingexactDiff = exactTotalInches - (totalNominalInches + approxFractionValue)against the unquantizedexactTotalIncheskeeps the tolerance badge honest even when display decimals are rounded.
2. Parse Inputs at the Boundary Instead of Coercing Empty Strings to Zero
In electrical power calculators, raw string inputs from form fields ("", " ", "-", "abc", "Infinity") frequently trip up naive Number(raw) wrappers. Because Number("") === 0 and Number(" ") === 0, deleting a voltage field silently passes 0 V into the formula—triggering division by zero or showing 0 A when the user actually cleared the field.
Follow a strict parse, don't validate boundary: convert raw strings once into number | null, rejecting empty strings and non-finite values immediately:
export function parseNumericInput(raw: string): number | null {
const trimmed = raw.trim();
if (trimmed === '') return null;
const parsed = Number(trimmed);
return Number.isFinite(parsed) ? parsed : null;
}
Downstream calculation functions accept number | null directly and return a discriminated union rather than throwing exceptions or returning sentinel zeros that UI components have to guess about:
export type CircuitType = 'dc' | 'single' | 'three_ll' | 'three_ln';
export type CalculationOutput =
| { ok: true; amps: number; continuousLoadAmps: number; mw: number; mva: number; mvar: number }
| { ok: false; errorCode: 'invalidVoltage' | 'invalidPower' | 'invalidPf' };
Notice how modeling CircuitType as a closed union ('dc' | 'single' | 'three_ll' | 'three_ln') solves another classic engineering bug: confusing three-phase line-to-line voltage (V_LL, multiplier √3 × PF) with three-phase line-to-neutral voltage (V_LN, multiplier 3 × PF). An exhaustive switch without a default branch lets TypeScript verify at compile time that both the solver and the step-by-step formula renderer handle all four topologies identically:
const SQRT_3 = Math.sqrt(3);
function resolveCircuitMultiplier(circuitType: CircuitType, pf: number): number {
switch (circuitType) {
case 'dc':
return 1;
case 'single':
return pf;
case 'three_ll':
return SQRT_3 * pf;
case 'three_ln':
return 3 * pf;
}
}
For DC circuits, the solver also enforces pf = 1.0 and mvar = 0 inside calculateMwToAmps regardless of whatever stale power-factor slider state the React UI happens to hold, keeping domain invariants inside pure TypeScript rather than scattered across component effects.
3. Lock Down Numeric Invariants & Round-Trips With Vitest
Because pure TypeScript calculation engines have zero DOM or network dependencies, edge-case regressions are cheap to catch with table-driven Vitest suites. Whenever we harden a converter, we test four categories explicitly:
-
Boundary parser rejections (
""," ","abc","Infinity",NaN, negative power, zero voltage). -
Carry-over & midpoint precision (
11 + 15.9/16in →1' 0",1.999ft →2' 0",1/128"at1/64"precision →1/64"). -
-0and non-finite guards (Object.is(res.totalDecimalInches, 0)on-0.000001). - Reciprocal round-trip invariants between inverse formulas (converting MW → Amps → MW must recover the original power within floating-point tolerance).
Here is how those invariants look in Vitest:
import { describe, it, expect } from 'vitest';
import { convertDecimalInchesToFraction, convertTenthsToInches } from './tenthsConverter';
import { calculateMwToAmps, parseNumericInput } from './mwToAmps';
import { calculateAmpToMw } from './ampToMw';
describe('numeric boundary & carry-over invariants', () => {
it('carries 15.9/16" and 1.999 ft into whole inches and feet', () => {
expect(convertDecimalInchesToFraction(11 + 15.9 / 16, 16).formattedStandard).toBe("1' 0\"");
expect(convertTenthsToInches(1.999, 16).formattedStandard).toBe("2' 0\"");
});
it('prevents -0 and "-0\' 0\\"" on sub-threshold negative inputs', () => {
const res = convertTenthsToInches(-0.000001, 16);
expect(res.isNegative).toBe(false);
expect(Object.is(res.totalDecimalInches, 0)).toBe(true);
expect(res.formattedStandard).toBe("0' 0\"");
});
it('never coerces blank or non-finite strings to 0', () => {
expect(parseNumericInput('')).toBeNull();
expect(parseNumericInput(' ')).toBeNull();
expect(parseNumericInput('Infinity')).toBeNull();
expect(
calculateMwToAmps({
circuitType: 'dc',
powerValue: null,
powerUnit: 'MW',
voltageValue: 480,
voltageUnit: 'V',
powerFactor: 1,
}),
).toEqual({ ok: false, errorCode: 'invalidPower' });
});
it('preserves MW -> Amps -> MW round-trip accuracy across AC topologies', () => {
const forward = calculateMwToAmps({
circuitType: 'three_ll',
powerValue: 5,
powerUnit: 'MW',
voltageValue: 11,
voltageUnit: 'kV',
powerFactor: 0.9,
});
expect(forward.ok).toBe(true);
if (!forward.ok) return;
const reverse = calculateAmpToMw({
circuitType: 'three_ll',
currentValue: forward.amps,
currentUnit: 'A',
voltageValue: 11,
voltageUnit: 'kV',
powerFactor: 0.9,
});
expect(reverse.isValid).toBe(true);
expect(reverse.mw).toBeCloseTo(5, 6);
});
});
Writing the round-trip assertion immediately surfaces subtle discrepancies—such as whether one converter rounds intermediate √3 values (1.732 vs. Math.sqrt(3)) or drops power factor on three_ln systems.
Wrapping Up
Keeping browser-local engineering tools trustworthy comes down to three habits: delay rounding until after fraction snapping, parse empty/invalid strings into explicit null and discriminated unions at the boundary, and enforce carry-over, -0, and round-trip invariants in unit tests rather than trusting manual spot checks.
If you want to inspect these behaviors interactively, the live implementations are running in our tenths-to-inches converter, MW-to-amps converter, and amps-to-MW converter.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.