convert-units

repository·main·Indexed 21 days ago

https://github.com/convert-units/convert-units

A utility for converting quantities between different units and systems, such as metric and imperial. It features a chained API, support for custom measure definitions, and a toBest() method to find the most appropriate unit for a value. The library provides built-in support for measures like area, digital storage, and energy, and includes TypeScript definitions for type-safe conversions.

Tokens
7.2K
Snippets
27
Records
32
Agent score
71%

What's inside convert-units

  1. Migrate from v2 to v3+

    main

    In versions v3.x and above, the default export of convert-units no longer contains all measures. Instead, you must use configureMeasurements along with a definitions object (like allMeasures) to initialize the converter.

    Old way (v2):

    import convert from 'convert-units';
    convert(1).from('m').to('mm');

    New way (v3+):

    import configureMeasurements from 'convert-units';
    import allMeasures from 'convert-units/definitions/all';  
    
    const convert = configureMeasurements(allMeasures);
    convert(1).from('m').to('mm');
  2. Extend existing measures with custom units

    main

    Since measure definitions are plain JavaScript objects, you can extend them by adding, removing, or changing units. To do this, import the existing measure definition, create a new object that spreads the existing systems and anchors, and add your custom unit definition (including a name object with singular and plural keys and a to_anchor value). Finally, use configureMeasurements to create a new converter instance with your extended measure.

    import configureMeasurements, {
      Measure
    } from 'convert-units';
    
    import
      length, {
      LengthSystems,
      LengthUnits,
    } from "convert-units/definitions/length"
    
    type NewLengthUnits = LengthUnits | 'px';
    const DPI = 96;
    const extendedLength: Measure<LengthSystems, NewLengthUnits> = {
      systems: {
        metric: {
          ...length.systems.metric,
          px: {
            name: {
              singular: 'Pixel',
              plural: 'Pixels',
            },
            to_anchor: 0.0254 / DPI,
          },
        },
        imperial: {
          ...length.systems.imperial,
        },
      },
      anchors: {
        ...length.anchors,
      },
    };
    
    const convert = configureMeasurements<'length', LengthSystems, NewLengthUnits>(
      { length: extendedLength }
    );
    
    convert(4).from('cm').to('px');
    // 151.18110236220474
  3. Use TypeScript for type-safe conversions

    main

    The library provides types for all packaged measures. By passing generic arguments to configureMeasurements<Measures, Systems, Units>, you enable IDE autocomplete and compile-time warnings if you attempt to use a unit that does not exist within the provided measures.

    To use all available measures with full type safety, import AllMeasures, AllMeasuresSystems, and AllMeasuresUnits from convert-units/definitions/all.

    import configureMeasurements from 'convert-units';
    import allMeasures, {
      AllMeasures,
      AllMeasuresSystems,
      AllMeasuresUnits,
    } from 'convert-units/definitions/all';
    
    const convertAll = configureMeasurements<
      AllMeasures,
      AllMeasuresSystems,
      AllMeasuresUnits
    >(allMeasures);
    
    convertAll(4).from('m2').to('cm2');
    // 400000
  4. Create custom measures

    main

    You can extend the library by defining custom measures. A measure consists of systems (collections of units) and anchors (rules for converting between systems).

    Unit Definition

    Each unit within a system requires:

    • name: An object with singular and plural strings.
    • to_anchor: A multiplier used to reach the system's base unit. The base unit must have a to_anchor of 1.
    • anchor_shift (optional): A value added/subtracted after the conversion (useful for temperature).

    System Conversion

    To allow conversion between different systems (e.g., System A to System B), define an anchors object. For each pair of systems, provide either:

    • ratio: A multiplier applied to the base unit of the source system to reach the base unit of the target system.
    • transform: A function (value) => number that converts the source base unit value to the target base unit value.

    Note: If both are provided, ratio takes precedence.

    const measure = {
      customMeasure: {
        systems: {
          A: {
            a: { name: { singular: 'a', plural: 'as' }, to_anchor: 1 },
            ah: { name: { singular: 'ah', plural: 'ahs' }, to_anchor: 10 },
          },
          B: {
            b: { name: { singular: 'b', plural: 'bs' }, to_anchor: 1 },
          }
        },
        anchors: {
          A: { B: { ratio: 2 } },
          B: { A: { ratio: 0.5 } }
        }
      }
    };
    
    const convert = configureMeasurements(measure);
    convert(1).from('a').to('b'); // 2
  5. Initialize convert-units with measurements

    main

    To use the library, you must first initialize it using configureMeasurements. You can either load all packaged measures or select specific ones to reduce bundle size (useful for Webpack or Rollup).

    import configureMeasurements from 'convert-units';
    import allMeasures from 'convert-units/definitions/all';
    
    // Option 1: Load everything
    const convert = configureMeasurements(allMeasures);
    
    // Option 2: Load specific measures for smaller bundles
    import volume from 'convert-units/definitions/volume';
    import mass from 'convert-units/definitions/mass';
    import length from 'convert-units/definitions/length';
    
    const convert = configureMeasurements({
        volume,
        mass,
        length,
    });
  6. Understand the Unit and Conversion data structures

    main

    When defining or inspecting units, the following interfaces are used:

    Unit Defines the properties of a single unit:

    • name: An object containing { singular: string, plural: string }.
    • to_anchor: The value used to convert to the system's anchor (can be a number, string, or Fraction).
    • anchor_shift: (Optional) A value added/subtracted during anchor conversion (e.g., for Celsius/Kelvin).

    UnitDescription Returned by .describe() and .list(). Provides a human-readable summary:

    • abbr: The unit abbreviation.
    • measure: The name of the measure.
    • system: The system the unit belongs to.
    • singular: The singular name.
    • plural: The plural name.
  7. Inspect measures and units

    main

    The convert instance provides several methods to inspect available measures, units, and their metadata.

    // List all configured measures
    convert().measures();
    // [ 'length', 'mass', 'volume', ... ]
    
    // List all units a specific unit can convert to
    convert().from('l').possibilities();
    // [ 'ml', 'l', 'tsp', 'Tbs', 'fl-oz', 'cup', 'pnt', 'qt', 'gal' ]
    
    // List all units belonging to a specific measure
    convert().possibilities('mass');
    // [ 'mcg', 'mg', 'g', 'kg', 'oz', 'lb', 'mt', 't' ]
    
    // List all configured units across all measures
    convert().possibilities();
    
    // Get detailed metadata for a single unit
    convert().describe('kg');
    // { abbr: 'kg', measure: 'mass', system: 'metric', singular: 'Kilogram', plural: 'Kilograms' }
    
    // List detailed descriptions for all units in a measure
    convert().list('mass');
    
    // List detailed descriptions for all configured units
    convert().list();
  8. Convert between units

    main

    Use the chained API to perform conversions. The library automatically handles conversions between different systems (e.g., metric to imperial). Note that attempting to convert between incompatible measures (e.g., mass to volume) will throw an error.

    // Basic conversion
    convert(1).from('l').to('ml');
    // 1000
    
    // Cross-system conversion (imperial to metric)
    convert(1).from('lb').to('kg');
    // 0.4536...
  9. Find the best unit with toBest()

    main

    The toBest() method finds the smallest unit within the same measure that results in a value $\ge 1$ (or $\le -1$ for negative numbers). You can customize this behavior using exclude and cutOffNumber options.

    // Find smallest unit with value >= 1
    convert(12000).from('mm').toBest();
    // { val: 12, unit: 'm', ... }
    
    // Exclude specific units
    convert(12000).from('mm').toBest({ exclude: ['m'] });
    // { val: 1200, unit: 'cm', ... }
    
    // Use a custom cut-off threshold
    convert(900).from('mm').toBest({ cutOffNumber: 10 });
    // { val: 90, unit: 'cm', ... }
    
    // Force a specific system
    convert(254).from('mm').toBest({ system: 'imperial' });
    // { val: 10, unit: 'in', plural: 'Inches' }
  10. Reference of packaged units

    main

    The following units are available out-of-the-box across various measures:

    Length: nm, μm, mm, cm, m, km, in, yd, ft-us, ft, fathom, mi, nMi
    Area: mm2, cm2, m2, ha, km2, in2, ft2, ac, mi2
    Mass: mcg, mg, g, kg, oz, lb, mt, st, t
    Volume: mm3, cm3, ml, l, kl, Ml, Gl, m3, km3, tsp, Tbs, in3, fl-oz, cup, pnt, qt, gal, ft3, yd3
    Volume Flow Rate: mm3/s, cm3/s, ml/s, cl/s, dl/s, l/s, l/min, l/h, kl/s, kl/min, kl/h, m3/s, m3/min, m3/h, km3/s, tsp/s, Tbs/s, in3/s, in3/min, in3/h, fl-oz/s, fl-oz/min, fl-oz/h, cup/s, pnt/s, pnt/min, pnt/h, qt/s, gal/s, gal/min, gal/h, ft3/s, ft3/min, ft3/h, yd3/s, yd3/min, yd3/h
    Temperature: C, F, K, R
    Time: ns, mu, ms, s, min, h, d, week, month, year, decade, century
    Frequency: Hz, mHz, kHz, MHz, GHz, THz, rpm, deg/s, rad/s
    Speed: m/s, km/h, mph, knot, ft/s, in/h, mm/h
    Torque: Nm, lbf-ft
    Pace: s/m, min/km, s/ft, min/mi
    Pressure: Pa, hPa, kPa, MPa, bar, torr, mH2O, mmHg, psi, ksi
    Digital: bit, byte, kb, Mb, Gb, Tb, kB, MB, GB, TB, KiB, MiB, GiB, TiB
    Illuminance: lx, ft-cd
    Parts-Per: ppm, ppb, ppt, ppq
    Voltage: V, mV, kV
    Current: A, mA, kA
    Power: W, mW, kW, MW, GW, PS, Btu/s, ft-lb/s, hp
    Apparent Power: VA, mVA, kVA, MVA, GVA
    Reactive Power: VAR, mVAR, kVAR, MVAR, GVAR
    Energy: Ws, Wm, Wh, mWh, kWh, MWh, GWh, J, kJ, MJ, GJ
    Reactive Energy: VARh, mVARh, kVARh, MVARh, GVARh
    Angle: deg, rad, grad, arcmin, arcsec
    Charge: c, mC, μC, nC, pC
    Force: N, kN, lbf, kgf
    Acceleration: g (g-force), m/s2, g0 (Standard Gravity)
    Pieces: pcs, bk-doz, cp, doz-doz, doz, gr-gr, gros, half-dozen, long-hundred, ream, scores, sm-gr, trio
  11. Perform unit conversions using .from() and .to()

    main

    The Converter class uses a fluent API to perform conversions. You must call .from(unitAbbr) to set the source unit, followed by .to(unitAbbr) to specify the target unit.

    Note on Order: You must call .from() before .to(). Calling them in the wrong order or calling .to() without a preceding .from() will throw an OperationOrderError.

    // Example conversion flow
    const result = convert(10).from('m').to('ft');