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
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:
TimeConverterfor time unitsLengthConverterfor length/distance unitsDataConverterfor data storage unitsTemperatureConverterfor temperature unitsMassConverterfor mass/weight unitsAreaConverterfor area unitsVolumeConverterfor volume unitsBaseConverterfor unknown or no units
Example
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
toAll()
Convert to all available units in the category.
Warning
Not available in BaseConverter
formatTo(targetUnit, options?)
Warning
Not available in BaseConverter
Format the converted value with various styling options.
FormatToOptions
| Property | Type | Description | Default |
|---|---|---|---|
style | 'compact' | 'scientific' | 'plural' | Output style. | 'plural' |
decimals | number | Number of decimal places. | 2 |
valueOf() / getValue()
Get the raw numeric value.
Internally used by JS engines to coerce to number.
getUnit()
Get the current unit.
toString()
Get formatted string with pluralization.
Internally used by JS engines to coerce to string.
format(decimals?)
Format the current value with pluralization.
supportedUnits(category?)
Get all supported units, optionally filtered by category.
toObject()
Get object representation.
toJSON()
Get JSON string representation.
Internally used by JS engines for JSON serialization.
Mathematical Operations
All converters support mathematical operations that return new instances:
abs()
Get absolute value.
round(decimals?)
Round to specified decimal places.
Comparison Methods
Category-Specific Details
TimeConverter
- Units:
nanosecond,microsecond,millisecond,second,minute,hour,day,week,month,year,decade,century,millennium - Base Unit:
second
LengthConverter
- Units:
millimeter,centimeter,meter,kilometer,inch,foot,yard,mile,nautical-mile,light-year(both US and UK spellings) - Base Unit:
meter
DataConverter
- Units:
bit,byte,kilobit,kilobyte,megabit,megabyte,gigabit,gigabyte,terabit,terabyte,petabit,petabyte - Base Unit:
byte
TemperatureConverter
- Units:
celsius,fahrenheit,kelvin - Special Notes: Temperature conversions use specific formulas rather than multiplication factors.
MassConverter
- Units:
microgram,milligram,gram,kilogram,tonne,ounce,pound,stone,short-ton,long-ton - Base Unit:
kilogram
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
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
Type Definitions
type $Unit = LooseLiteral<UnitMap[Category]>;
type FormatToOptions = {
style?: 'compact' | 'scientific' | 'plural';
decimals?: number;
};Notes & Limitations
Important Notes
- Unit Detection: The converter automatically detects the category based on the provided unit string. Unknown units will use the base converter.
- Mathematical Operations: Operations like
add(),subtract(), etc. assume the same unit and return new instances rather than modifying the original. - Pluralization: The automatic pluralization adds
"s"for values > 1. For complex pluralization needs, consider using the sharedpluralizerinstance orPluralizerclass. - Temperature Conversions: Temperature uses special conversion formulas rather than multiplicative factors due to the different scales.
- 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
NaNvalues will propagate theNaN.
Last updated: Sun, Jun 14, 2026 07:31:07PM (UTC)
