BBizKit

qty.parse

v0.1.0 latest

Parse a UCUM-compatible quantity string into a { value, unit } object using greedy numeric prefix extraction.

quantityparsingmeasurementucumiotsensors

Parse a UCUM-compatible quantity string into a { value, unit } object using greedy numeric prefix extraction.

Signature

function parse(input: string): Quantity | null

Type Definitions:

Problem

Measurement strings from IoT sensors, user input, and APIs combine numbers and units in a single string (e.g. '42.5 kg', '1.5e3 m/s'). Extracting the numeric and unit portions requires careful parsing that handles decimals, negatives, and scientific notation.

How It Works

Uses greedy numeric prefix extraction: the longest leading numeric match becomes value, the remainder (after trimming) becomes unit. Supports scientific notation.

Boundaries

  • Returns null if no numeric prefix found, or no unit remains after extraction.
  • Throws TypeError for non-string input.
  • Scientific notation is supported (e.g. '1.5e3 kg' → { value: 1500, unit: 'kg' }).
  • Unit comparison is case-sensitive ('kg' !== 'Kg').
  • Does not validate that the unit is a recognized UCUM or SI unit.

Replaces

Common boilerplate this function replaces:

const match = input.match(/^([\d.]+)\s*(\w+)$/); if (match) { return { value: parseFloat(match[1]), unit: match[2] }; }

Examples

qty.parse("42.5 kg");  // { value: 42.5, unit: "kg" }
qty.parse("1.5e3 m/s");  // { value: 1500, unit: "m/s" }
qty.parse("-10 °C");  // { value: -10, unit: "°C" }
qty.parse("42");  // null
qty.parse("kg");  // null

Standards

Caveats

  • Units are not validated — any non-empty string after the number is accepted.
  • Uses IEEE 754 double for value — subject to floating-point precision limits for very large or very precise values.

FAQ

How to parse a measurement string in JavaScript?

qty.parse('42.5 kg') returns { value: 42.5, unit: 'kg' }. Handles decimals, negatives, and scientific notation.

Does qty.parse validate units?

No. Any string after the numeric prefix is accepted as the unit.

Can qty.parse handle scientific notation?

Yes. qty.parse('1.5e3 W') returns { value: 1500, unit: 'W' }.

What happens with no unit?

Returns null. Both a numeric value and a unit are required.

Is unit comparison case-sensitive?

Yes. 'kg' and 'Kg' are different units. qty.add rejects mismatched units.