Toolbox-XToolbox-X

Converter

Converter class for robust, type-safe measurement conversion across time, length, data, temperature, mass, area, and volume.

Converter & Unit Conversion Classes

The Unit Converter system provides a comprehensive solution for converting values between different measurement units across multiple categories including time, length, data, temperature, mass, area, and volume.

The system consists of a main Converter function and specialized converter classes that automatically handle unit detection and provide type-safe conversion methods.


Features

  • Automatic unit detection based on input unit
  • Type-safe conversions with full TypeScript support
  • Multiple output formats: compact, scientific, and pluralized
  • Mathematical operations: add, subtract, multiply, divide
  • Batch conversions with .toAll() method
  • Custom formatting with decimal control
  • Comprehensive unit support across 7 categories
  • Easy-to-use API with intuitive methods
  • Extensible architecture for future unit categories (More to come!)

Import

import { 
  Converter, 
  converter, // Alias for Converter
  TimeConverter,
  LengthConverter, 
  DataConverter,
  TemperatureConverter,
  MassConverter,
  AreaConverter,
  VolumeConverter
} from 'toolbox-x/converter';

Usage Examples

playground.ts

Converter Function

Converter(value, unit?)

The main converter function that automatically detects the unit category and returns the appropriate converter instance.

function Converter<U extends $Unit>(value: Numeric, unit?: U): Converted<U>

Parameters

  • value (Numeric): The numeric value to convert (number or numeric string).
  • unit ($Unit): The source unit (optional for base converter).

Returns

  • Returns a specialized converter instance based on the unit category:
    • TimeConverter for time units
    • LengthConverter for length/distance units
    • DataConverter for data storage units
    • TemperatureConverter for temperature units
    • MassConverter for mass/weight units
    • AreaConverter for area units
    • VolumeConverter for volume units
    • BaseConverter for unknown or no units

Example

playground.ts

Converter Classes

All converter classes share common methods from the base class and provide category-specific conversion capabilities.

Available Classes

  • TimeConverter - Time units (seconds, minutes, hours, days, etc.)
  • LengthConverter - Length/distance units (meters, feet, miles, etc.)
  • DataConverter - Data storage units (bytes, kilobytes, megabytes, etc.)
  • TemperatureConverter - Temperature units (celsius, fahrenheit, kelvin)
  • MassConverter - Mass/weight units (grams, kilograms, pounds, etc.)
  • AreaConverter - Area units (square meters, acres, hectares, etc.)
  • VolumeConverter - Volume units (liters, gallons, cubic meters, etc.)

Common Methods (All Converters)

All converter instances inherit these methods from the base class:

to(targetUnit)

Convert to a specific target unit.

Warning

Not available in BaseConverter

playground.ts

toAll()

Convert to all available units in the category.

Warning

Not available in BaseConverter

playground.ts

formatTo(targetUnit, options?)

Warning

Not available in BaseConverter

Format the converted value with various styling options.

playground.ts

FormatToOptions

PropertyTypeDescriptionDefault
style'compact' | 'scientific' | 'plural'Output style.'plural'
decimalsnumberNumber of decimal places.2

valueOf() / getValue()

Get the raw numeric value.

Internally used by JS engines to coerce to number.

playground.ts

getUnit()

Get the current unit.

playground.ts

toString()

Get formatted string with pluralization.

Internally used by JS engines to coerce to string.

playground.ts

format(decimals?)

Format the current value with pluralization.

playground.ts

supportedUnits(category?)

Get all supported units, optionally filtered by category.

playground.ts

toObject()

Get object representation.

playground.ts

toJSON()

Get JSON string representation.

Internally used by JS engines for JSON serialization.

playground.ts

Mathematical Operations

All converters support mathematical operations that return new instances:

playground.ts

abs()

Get absolute value.

playground.ts

round(decimals?)

Round to specified decimal places.

playground.ts

Comparison Methods

playground.ts

Category-Specific Details

TimeConverter

  • Units: nanosecond, microsecond, millisecond, second, minute, hour, day, week, month, year, decade, century, millennium
  • Base Unit: second
playground.ts

LengthConverter

  • Units: millimeter, centimeter, meter, kilometer, inch, foot, yard, mile, nautical-mile, light-year (both US and UK spellings)
  • Base Unit: meter
playground.ts

DataConverter

  • Units: bit, byte, kilobit, kilobyte, megabit, megabyte, gigabit, gigabyte, terabit, terabyte, petabit, petabyte
  • Base Unit: byte
playground.ts

TemperatureConverter

  • Units: celsius, fahrenheit, kelvin
  • Special Notes: Temperature conversions use specific formulas rather than multiplication factors.
playground.ts

MassConverter

  • Units: microgram, milligram, gram, kilogram, tonne, ounce, pound, stone, short-ton, long-ton
  • Base Unit: kilogram
playground.ts

AreaConverter

  • Units: square-millimeter, square-centimeter, square-meter, square-kilometer, square-inch, square-foot, square-yard, square-mile, hectare, acre (both US and UK spellings)
  • Base Unit: square-meter
playground.ts

VolumeConverter

  • Units: cubic-millimeter, cubic-centimeter, cubic-meter, cubic-kilometer, cubic-inch, cubic-foot, cubic-yard, liter, milliliter, gallon, quart, pint, cup, tablespoon, teaspoon (both US and UK spellings)
  • Base Unit: cubic-meter
playground.ts

Type Definitions

type $Unit = LooseLiteral<UnitMap[Category]>;
type FormatToOptions = {
  style?: 'compact' | 'scientific' | 'plural';
  decimals?: number;
};

Notes & Limitations

Important Notes

  1. Unit Detection: The converter automatically detects the category based on the provided unit string. Unknown units will use the base converter.
  2. Mathematical Operations: Operations like add(), subtract(), etc. assume the same unit and return new instances rather than modifying the original.
  3. Pluralization: The automatic pluralization adds "s" for values > 1. For complex pluralization needs, consider using the shared pluralizer instance or Pluralizer class.
  4. Temperature Conversions: Temperature uses special conversion formulas rather than multiplicative factors due to the different scales.
  5. Precision: Conversions may have minor precision limitations in few cases with very large or very small values due to floating-point arithmetic.

Best Practices

  • Use TypeScript for full type safety and autocomplete support.
  • Chain operations for complex calculations:
    Converter('90', 'minute').add('30').to('hour'); // 2
  • Use .toAll() when you need multiple conversions for display purposes.
  • Prefer .formatTo() for user-facing outputs with proper labeling.

Error Handling

  • Invalid numeric values will be converted to NaN.
  • Unknown units will use the base converter with limited functionality.
  • Mathematical operations on NaN values will propagate the NaN.

Last updated: Sun, Jun 14, 2026 07:31:07PM (UTC)

On this page