Unit

Conversion

Convert length, mass, area, volume, temperature, data, and time units.

Conversion

convert is smallest API surface. Use it when input already clean and units already known.

import {
  bestUnit,
  convert,
  convertDetailed,
  convertMany,
  normalizeMixedMeasurement,
  parseMixedMeasurement,
} from "@coreify/unit"

convert(1, "km", "m") // 1000
convert(32, "f", "c") // 0
convert(1, "bigha", "katha", { precision: 2 }) // 20

convertMany(1, "kg", ["g", "lb"], { precision: 3 })
// { g: 1000, lb: 2.205 }

When to use which conversion API

  • convert for single target, plain number result
  • convertMany for dashboards, compare tables, exports
  • convertDetailed when app must inspect how result was produced
  • bestUnit when UI should choose readable unit instead of forcing fixed target

Mixed measurements

Mixed parsing matters when input comes from humans, legacy CSVs, OCR, chat-like UI, or admin panels.

parseMixedMeasurement("5 ft 7 in")
// { category: "length", terms: [{ value: 5, unit: "ft" }, { value: 7, unit: "in" }] }

normalizeMixedMeasurement("২ মি ৩০ সেমি", "cm")
// 230

Use parseMixedMeasurement when app wants structured terms. Use normalizeMixedMeasurement when app wants one final numeric result.

Smart units and traces

bestUnit(1532, "m", { precision: 3 })
// { value: 1.532, unit: "km", formatted: "1.532 km" }

convertDetailed(1, "bigha", "sq_ft")
// { value, rawValue, baseValue, factors, status, warnings }

Regional units such as seer, mon, katha, and bigha add warning entries so app can flag them for review.

convertDetailed is useful when:

  • precision loss must be visible
  • audit log needs intermediate values
  • import review UI should explain suspicious conversions
  • regulated or domain-heavy flow cannot hide rounding behavior

Precision and rounding

convert(1, "m", "ft", { precision: 2 }) // 3.28
convert(1, "m", "ft", { precision: 2, roundingMode: "ceil" }) // 3.29
convert(1, "m", "ft", { precision: 2, roundingMode: "floor" }) // 3.28

Supported rounding modes: half-up, floor, ceil, trunc, expand.

Practical rule:

  • use precision for output shape
  • use roundingMode for business rule
  • use convertDetailed when rounded and raw values both matter

Categories

Unit rejects category mismatches:

convert(1, "kg", "m") // throws IncompatibleUnitError

That guard matters because generic converter snippets often fail silently at app layer. Unit keeps category boundary explicit.

Conversion errors

Errors now try to say what caller should change.

convert(1, "kg", "banana")
// UnknownUnitError:
// Unit "banana" is not recognized. Use known unit ids, symbols, or aliases like "kg", "meter", or "sq_ft".

convert(1, "kg", "m")
// IncompatibleUnitError:
// Cannot convert "kg" to "m" because they are different measurement categories.

On this page