units.parse-quantity
Parse "2.5 kg", "1,200 m" or "12 ft 6 in" into an exact decimal value and a canonical unit symbol, strictly.
1.0.0 · published 2026-10-03 by charlie · Anterra
Pinned by 31 tests, run in TypeScript, Python and Rust.
What it does
Turns what a person typed into a value and a canonical unit that `units.convert` accepts: `"2.5 kg"`, `"1,200 m"`, `"12 ft 6 in"`, `"5'11\""`. The value is decimal text, never a float, so nothing is lost between parsing and converting.
## Grammar
For example
parseQuantity(2.5 kg)→ value 2.5, unit kg, dimension mass a decimal and a symbolparseQuantity(1,200 m)→ value 1200, unit m, dimension length thousands separators are removedparseQuantity(12 ft 6 in)→ value 150, unit in, dimension length feet and inches sum exactly into inches
The function
The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.
export function parseQuantity(text: string): Quantity
| text | string | a number and a unit, or a compound such as "5 lb 3 oz" (largest unit first) |
| returns | Quantity | a compound is summed exactly into its last (smallest) unit |
The type it declares, generated into your project
/** A parsed quantity, ready to hand to units.convert. */
export interface Quantity {
/** plain decimal text: commas removed, trailing zeros trimmed */
readonly value: string;
/** canonical units.convert symbol, e.g. "in", "gal_us", "degC" */
readonly unit: string;
/** length, mass, area, volume, temperature or energy */
readonly dimension: string;
}
Your code names it in one line, in the file that uses it
import { parseQuantity } from "#fune/units.parse-quantity@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { UNITS, type UnitDefinition } from "./units_convert_data.ts"; ← units.convert’s rule data (^1.0.0) · built alongside by fune
import { UNIT_ALIASES } from "./units_parse_quantity_data.ts"; ← this capability’s own data, compiled from data/aliases.json into the same file by fune build
import { type Quantity } from "./units_parse_quantity_types.ts";
const MAX_DIGITS = 15;
// Explicit sets rather than regex classes: \s and toLowerCase() differ between
// languages on non-ASCII input, and these must not.
function isSpace(c: string): boolean {
return c === " " || c === "\t" || c === "\n" || c === "\r";
}
function isDigit(c: string): boolean {
return c >= "0" && c <= "9";
}
function asciiLower(s: string): string {
return s.replace(/[A-Z]/g, (c) => c.toLowerCase());
}
function allDigits(s: string): boolean {
return s.length > 0 && [...s].every(isDigit);
}
function trimSpace(s: string): string {
let a = 0;
let b = s.length;
while (a < b && isSpace(s[a])) a++;
while (b > a && isSpace(s[b - 1])) b--;
return s.slice(a, b);
}
function wellGrouped(whole: string): boolean {
if (!whole.includes(",")) return allDigits(whole);
const groups = whole.split(",");
return groups[0].length >= 1 && groups[0].length <= 3 && allDigits(groups[0]) && groups.slice(1).every((g) => g.length === 3 && allDigits(g));
}
type Part = { written: string; whole: bigint; fraction: string; unit: UnitDefinition };
function parseNumber(written: string): { whole: bigint; fraction: string } {
const pieces = written.split(".");
const plain = written.split(",").join("");
const plainPieces = plain.split(".");
const plainOk = plainPieces.length <= 2 && allDigits(plainPieces[0]) && (plainPieces.length === 1 || allDigits(plainPieces[1]));
const ok = pieces.length <= 2 && wellGrouped(pieces[0]) && (pieces.length === 1 || allDigits(pieces[1]));
if (!ok) {
if (written.includes(",") && plainOk) throw new RangeError(`bad thousands grouping in "${written}"`);
throw new RangeError(`malformed number "${written}"`);
}
const whole = plainPieces[0].replace(/^0+/, "");
const fraction = (plainPieces[1] ?? "").replace(/0+$/, "");
if ((whole + fraction).replace(/^0+/, "").length > MAX_DIGITS || fraction.length > MAX_DIGITS) {
throw new RangeError(`number "${written}" has too many digits: at most 15 significant digits and 15 decimal places`);
}
return { whole: BigInt(whole === "" ? "0" : whole), fraction };
}
function unitBySymbol(symbol: string): UnitDefinition {
const found = UNITS.find((u) => u.symbol === symbol);
// Only reachable if the alias table and units.convert drift apart.
if (!found) throw new RangeError(`alias table names unit "${symbol}", which units.convert does not define`);
return found;
}
function resolveUnit(text: string): UnitDefinition {
const exactUnit = UNITS.find((u) => u.symbol === text);
if (exactUnit) return exactUnit;
const exactAlias = UNIT_ALIASES.find((a) => a.alias === text);
if (exactAlias) {
if (exactAlias.symbol === null) throw new RangeError(`ambiguous unit "${text}": use ${exactAlias.choices}`);
return unitBySymbol(exactAlias.symbol);
}
// Case-insensitive fallback, so "KG" and "Feet" work. Where two spellings
// differ only in case and mean different things ("cal" and food "Cal"),
// the ambiguity wins rather than a guess.
const lower = asciiLower(text);
const ambiguous = UNIT_ALIASES.find((a) => a.symbol === null && asciiLower(a.alias) === lower);
if (ambiguous) throw new RangeError(`ambiguous unit "${text}": use ${ambiguous.choices}`);
const symbols: string[] = [];
for (const u of UNITS) if (asciiLower(u.symbol) === lower && !symbols.includes(u.symbol)) symbols.push(u.symbol);
for (const a of UNIT_ALIASES) if (a.symbol !== null && asciiLower(a.alias) === lower && !symbols.includes(a.symbol)) symbols.push(a.symbol);
if (symbols.length === 1) return unitBySymbol(symbols[0]);
if (symbols.length > 1) throw new RangeError(`ambiguous unit "${text}": letter case matters, use ${symbols.join(" or ")}`);
throw new RangeError(`unknown unit "${text}"`);
}
function format(negative: boolean, whole: bigint, fraction: string): string {
const text = whole.toString() + (fraction === "" ? "" : "." + fraction);
return negative && (whole !== 0n || fraction !== "") ? "-" + text : text;
}
/**
* Parse a written quantity into an exact decimal value and a canonical unit.
*
* A compound such as "12 ft 6 in" is summed into its last unit ("150" in)
* using exact whole-number ratios, which is why mixing systems ("1 ft 2 cm")
* is refused rather than approximated.
*/
export function parseQuantity(text: string): Quantity {
if (typeof text !== "string") throw new TypeError("quantity text must be a string");
const src = trimSpace(text);
if (src === "") throw new RangeError("quantity text is empty");
let negative = false;
const parts: Part[] = [];
let i = 0;
while (i < src.length) {
while (i < src.length && isSpace(src[i])) i++;
const start = i;
if (src[i] === "-") {
if (parts.length > 0) throw new RangeError(`only the first number may be negative: "${src}"`);
negative = true;
i++;
}
const numberStart = i;
while (i < src.length && (isDigit(src[i]) || src[i] === "," || src[i] === ".")) i++;
const written = src.slice(numberStart, i);
if (written === "") throw new RangeError(`expected a number at "${src.slice(start)}"`);
const { whole, fraction } = parseNumber(written);
const unitStart = i;
while (i < src.length && !isDigit(src[i]) && src[i] !== "-") i++;
const unitText = trimSpace(src.slice(unitStart, i))
.split(/[ \t\n\r]+/)
.join(" ");
if (unitText === "") throw new RangeError(`missing unit after "${written}"`);
parts.push({ written, whole, fraction, unit: resolveUnit(unitText) });
}
const last = parts[parts.length - 1];
if (parts.length === 1) {
return { value: format(negative, last.whole, last.fraction), unit: last.unit.symbol, dimension: last.unit.dimension };
}
for (let k = 1; k < parts.length; k++) {
const prev = parts[k - 1].unit;
const cur = parts[k].unit;
if (cur.dimension !== prev.dimension) {
throw new RangeError(`cannot combine ${prev.symbol} (${prev.dimension}) and ${cur.symbol} (${cur.dimension}) in one quantity`);
}
if (cur.dimension === "temperature") throw new RangeError(`temperatures cannot be compound: "${src}"`);
if (cur.symbol === prev.symbol) throw new RangeError(`unit "${cur.symbol}" appears twice in "${src}"`);
const curSize = BigInt(cur.factorNumerator) * BigInt(prev.factorDenominator);
const prevSize = BigInt(prev.factorNumerator) * BigInt(cur.factorDenominator);
if (curSize >= prevSize) throw new RangeError(`units must run from largest to smallest: "${prev.symbol}" cannot come before "${cur.symbol}"`);
}
let total = last.whole;
for (const part of parts.slice(0, -1)) {
if (part.fraction !== "") {
throw new RangeError(`only the last number of a compound quantity may have a fraction: "${src}"`);
}
const num = BigInt(part.unit.factorNumerator) * BigInt(last.unit.factorDenominator);
const den = BigInt(part.unit.factorDenominator) * BigInt(last.unit.factorNumerator);
if (num % den !== 0n) {
throw new RangeError(`cannot combine ${part.unit.symbol} and ${last.unit.symbol} exactly: 1 ${part.unit.symbol} is not a whole number of ${last.unit.symbol}`);
}
total += part.whole * (num / den);
}
return { value: format(negative, total, last.fraction), unit: last.unit.symbol, dimension: last.unit.dimension };
}Install
fune build
With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 1 dependency, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:
fune add units.parse-quantity
The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./units.parse-quantity-1.0.0-typescript.fune, or fetch it from a terminal with fune pull units.parse-quantity@1.0.0:typescript.
The whole function, every language, is one file too: units.parse-quantity-1.0.0.fune, 48,085 bytes, sha256 8edaf9580576a532d30ec6a175c43a336e2e53ee57d48381fc833377b290fa8c. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
// fune: before units.parse-quantity
after — your function gets the result and the arguments, and returns the final result.
// fune: after units.parse-quantity
replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.
// fune: replace units.convert in units.parse-quantity
step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show units.parse-quantity --steps.
// fune: step units.parse-quantity after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
| Case | Arguments | Expected | |
|---|---|---|---|
| a decimal and a symbol | 2.5 kg | → | value 2.5, unit kg, dimension mass |
| thousands separators are removed | 1,200 m | → | value 1200, unit m, dimension length |
| feet and inches sum exactly into inches | 12 ft 6 in | → | value 150, unit in, dimension length |
| prime and double-prime marks | 5'11" | → | value 71, unit in, dimension length |
| a fraction on the last part is kept | 5 ft 11.5 in | → | value 71.5, unit in, dimension length |
| pounds and ounces | 5 lb 3 oz | → | value 83, unit oz, dimension mass |
| stones and pounds | 11 st 4 lb | → | value 158, unit lb, dimension mass |
| metric compounds work too | 1 m 5 cm | → | value 105, unit cm, dimension length |
| a negative sign applies to the whole compound | -5 ft 3 in | → | value -63, unit in, dimension length |
| word units in any letter case, trailing zeros trimmed | 2.50 Kilograms | → | value 2.5, unit kg, dimension mass |
Show the other 21 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| degree sign temperature, negative | -40 °F | → | value -40, unit degF, dimension temperature |
| grouped digits with a fraction | 12,345,678.90 mL | → | value 12345678.9, unit mL, dimension volume |
| a two-word unit | 8 US fl oz | → | value 8, unit floz_us, dimension volume |
| no space between number and unit, leading zeros dropped | 007kWh | → | value 7, unit kWh, dimension energy |
| negative zero is zero | -0.0 kg | → | value 0, unit kg, dimension mass |
| square feet | 3 sq ft | → | value 3, unit ft2, dimension area |
| empty text | → | error: quantity text is empty | |
| a unit with no number | kg | → | error: expected a number at "kg" |
| a number with no unit | 12 | → | error: missing unit after "12" |
| bad thousands grouping | 1,20 m | → | error: bad thousands grouping in "1,20" |
| two decimal points | 1.2.3 m | → | error: malformed number "1.2.3" |
| unknown unit | 3 furlongs | → | error: unknown unit "furlongs" |
| a bare gallon is ambiguous | 2 gal | → | error: ambiguous unit "gal": use gal_us or gal_imp |
| food Calorie is not the calorie symbol, whatever the case | 250 CAL | → | error: ambiguous unit "CAL": use cal (thermochemical calorie) or kcal (food Calorie) |
| smallest unit first is refused | 6 in 12 ft | → | error: units must run from largest to smallest: "in" cannot come before "ft" |
| mixed dimensions are refused | 5 ft 3 lb | → | error: cannot combine ft (length) and lb (mass) in one quantity |
| mixed systems cannot sum exactly | 1 ft 2 cm | → | error: cannot combine ft and cm exactly: 1 ft is not a whole number of cm |
| a fraction before the last part is refused | 5.5 ft 3 in | → | error: only the last number of a compound quantity may have a fraction |
| a minus sign inside a compound is refused | 5 ft -3 in | → | error: only the first number may be negative |
| temperatures are never compound | 10 degC 5 K | → | error: temperatures cannot be compound |
| more than 15 significant digits | 1234567890123456 m | → | error: has too many digits |
More from the author
One or more parts separated by whitespace; each part is a number, optional whitespace, then a unit. The unit runs until the next digit, so two-word units ("fl oz", "sq ft", "US gallon") work.
- Numbers are ASCII digits with an optional `.` fraction. Thousands separators are allowed only as strict groups of three (`1,200`, `12,345,678`); `1,20` is refused rather than guessed at, because in half the world it means 1.20. At most 15 significant digits and 15 decimal places, as in `units.convert`. - A leading `-` is allowed on the first number only, and negates the whole quantity: `-5 ft 3 in` is -63 in. - The value comes back normalised: commas removed, leading zeros and trailing fractional zeros trimmed, and `-0` written as `0`.
## Units
A unit is matched first as a `units.convert` symbol (`kg`, `gal_us`, `degC`), then as an alias from `data/aliases.json` (`kilograms`, `lbs`, `feet`, `'`, `°C`, `sq ft`), then both again ignoring ASCII letter case (`KG`, `Feet`). Only ASCII letters fold, so the answer is the same in every language.
Words that mean different things in different places are refused with the choices spelled out, instead of silently picking one: `gal`, `pint`, `quart`, `fl oz` (US or imperial), `cup`, `ton` (tonne, short or long) and `Cal`/`calorie` (a food Calorie is a kilocalorie). The case-insensitive step never hides this: `CAL` is ambiguous even though `cal` is a symbol. A bare `oz` is the avoirdupois ounce of mass; say `US fl oz` for volume.
Every alias names a symbol that `units.convert` defines; the implementation reads `units.convert`'s own table, so the two cannot drift apart.
## Compound quantities
`12 ft 6 in` is returned as `150 in`: the parts are summed exactly into the last, smallest unit. For that to be exact, the rules are strict:
- every part has the same dimension, and temperatures are never compound; - units run from largest to smallest and never repeat; - only the last number may have a fraction (`5 ft 11.5 in`, not `5.5 ft 3 in`); - each earlier unit must be a whole number of the last one, so `1 ft 2 cm` (30.48 cm per foot) is refused rather than approximated.
Files
| Path | Bytes |
|---|---|
| README.md | 2,421 |
| data/aliases.json | 11,467 |
| impl/python.py | 7,089 |
| impl/rust.rs | 9,215 |
| impl/typescript.ts | 7,482 |
| vectors.json | 4,148 |