Skip to content

Getting Started

This guide walks you through installing @devhaven/unit-conversion, importing it across different JavaScript runtimes, and configuring your first unit conversions.

Install @devhaven/unit-conversion from the npm registry using your preferred package manager:

Terminal window
npm i @devhaven/unit-conversion

@devhaven/unit-conversion is also published to JSR with native TypeScript support:

Terminal window
deno add jsr:@devhaven/unit-conversion

The package ships with both ES Modules (ESM) and CommonJS (CJS) builds alongside bundled TypeScript declaration files (.d.ts).

import { Conversion, UNITS, LABELS } from "@devhaven/unit-conversion";
  1. Create a Conversion instance

    Instantiate Conversion with default settings (isFloat: true, decimals: 2) or pass a custom configuration object:

    import { Conversion } from "@devhaven/unit-conversion";
    // Default configuration: { isFloat: true, decimals: 2, locale: undefined }
    const convert = new Conversion();
    // Custom configuration
    const preciseConvert = new Conversion({
    decimals: 4,
    isFloat: true,
    locale: "en-US",
    });
  2. Convert values with .from() and .to()

    Pass a number or numeric string directly to the convert function (or call convert.value(...)), specify the source unit with .from(), and choose the target unit with .to():

    // Callable syntax (recommended)
    const length = convert(25).from("kilometer").to("mile");
    console.log(length);
    // { value: 15.53, unit: "mi" }
    // Method syntax (backward-compatible)
    const temp = convert.value("100").from("celsius").to("kelvin");
    console.log(temp);
    // { value: 373.15, unit: "K" }
  3. Use exported constants & TypeScript types

    In addition to Conversion, you can import unit lists, unit symbol labels, and TypeScript union types for building UIs or validating inputs:

    import {
    UNITS,
    LABELS,
    getUnitCategory,
    type AllUnits,
    type LengthUnits,
    type ConversionConfig,
    } from "@devhaven/unit-conversion";
    // List all supported length units
    console.log(UNITS.length);
    // ["meter", "kilometer", "centimeter", "millimeter", "inch", "foot", "yard", "mile"]
    // Look up the display symbol for a unit
    console.log(LABELS.kilometer); // "km"
    console.log(LABELS.celsius); // "°C"
    // Determine which category a unit belongs to
    console.log(getUnitCategory("pascal")); // "pressure"