CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mathjs

Math.js is an extensive math library for JavaScript and Node.js featuring a flexible expression parser, symbolic computation, and support for numbers, big numbers, complex numbers, fractions, units, and matrices.

84

1.47x
Overview
Eval results
Files

units.mddocs/

Units and Conversions

This document covers Math.js's comprehensive unit system, including unit creation, conversion, arithmetic with units, and the extensive built-in unit library covering physical quantities, measurements, and conversions.

Import

import {
  // Core unit functions
  unit, to, createUnit, splitUnit, toBest,
  // Unit-related utilities
  isUnit, hasNumericValue,
  // Mathematical operations (work with units)
  add, subtract, multiply, divide, pow, sqrt,
  // Constants with units (physical constants)
  speedOfLight, planckConstant, electronMass, avogadro
} from 'mathjs'

Basic Unit Creation and Usage

Creating Units

unit(value?: string | number, unit?: string): Unit

{ .api }

// Create units from strings
unit('5 meter') // 5 meter
unit('10 cm') // 10 cm  
unit('3.5 kg') // 3.5 kg
unit('25 celsius') // 25 celsius

// Create dimensionless units
unit('5') // Just the number 5
unit() // Dimensionless 1

// Create units with separate value and unit
unit(5, 'meter') // 5 meter
unit(3.14159, 'radian') // π radians

// Complex values with units  
unit(complex(3, 4), 'meter') // (3+4i) meter
unit(fraction(1, 3), 'hour') // 1/3 hour

// From expressions
unit('5 * 3 meter') // 15 meter
unit('sqrt(16) kg') // 4 kg

Unit Conversion

to(value: Unit, unit: string | Unit): Unit

{ .api }

// Basic conversions
const distance = unit('5 km')
to(distance, 'meter') // 5000 meter
to(distance, 'mile') // ~3.10686 mile
to(distance, 'inch') // ~196850 inch

// Temperature conversions
const temp = unit('100 celsius')
to(temp, 'fahrenheit') // 212 fahrenheit  
to(temp, 'kelvin') // 373.15 kelvin

// Time conversions
const time = unit('2 hours')
to(time, 'minute') // 120 minute
to(time, 'second') // 7200 second

// Area conversions
const area = unit('1 m^2')
to(area, 'cm^2') // 10000 cm^2
to(area, 'ft^2') // ~10.7639 ft^2

// Volume conversions
const volume = unit('1 liter')
to(volume, 'gallon') // ~0.264172 gallon
to(volume, 'm^3') // 0.001 m^3

// Compound units
const speed = unit('60 mile/hour')
to(speed, 'km/h') // ~96.5606 km/h
to(speed, 'm/s') // ~26.8224 m/s

Automatic Best Unit Selection

toBest(value: Unit, options?: ToBestOptions): Unit

{ .api }

interface ToBestOptions {
  system?: 'si' | 'us' | 'imperial' | 'metric'
}
// Automatically choose the most readable unit
toBest(unit('0.001 m')) // 1 mm
toBest(unit('1000 m')) // 1 km
toBest(unit('3600 second')) // 1 hour

// With system preference
toBest(unit('1000 meter'), { system: 'us' }) // ~0.621371 mile
toBest(unit('1 kg'), { system: 'us' }) // ~2.20462 lb

// For very large or small quantities
toBest(unit('0.000001 meter')) // 1 micrometer  
toBest(unit('1000000 gram')) // 1 tonne

Unit Arithmetic

Basic Operations with Units

// Addition and subtraction (units must be compatible)
add(unit('5 meter'), unit('3 meter')) // 8 meter
add(unit('2 km'), unit('500 m')) // 2.5 km (automatic conversion)
subtract(unit('10 inch'), unit('2 inch')) // 8 inch

// Multiplication and division
multiply(unit('5 meter'), unit('3 meter')) // 15 meter^2
multiply(unit('60 km'), unit('2 hour')) // Error: incompatible for this operation
divide(unit('60 km'), unit('2 hour')) // 30 km/hour

// With scalars
multiply(unit('5 meter'), 3) // 15 meter
divide(unit('10 kg'), 2) // 5 kg

// Powers and roots
pow(unit('5 meter'), 2) // 25 meter^2  
pow(unit('8 m^3'), 1/3) // 2 meter
sqrt(unit('16 meter^2')) // 4 meter

Complex Unit Operations

// Force calculation: F = ma
const mass = unit('5 kg')
const acceleration = unit('10 m/s^2')  
const force = multiply(mass, acceleration) // 50 N (automatically converts to Newtons)

// Energy calculation: E = 0.5 * m * v^2
const velocity = unit('20 m/s')
const kineticEnergy = multiply(0.5, multiply(mass, pow(velocity, 2))) // 1000 J

// Pressure calculation: P = F/A
const area = unit('2 m^2')
const pressure = divide(force, area) // 25 Pa

// Electrical calculations
const voltage = unit('12 V')
const current = unit('2 A')  
const power = multiply(voltage, current) // 24 W
const resistance = divide(voltage, current) // 6 ohm

Creating Custom Units

Simple Custom Units

createUnit(name: string, definition?: string | Unit | UnitDefinition, options?: CreateUnitOptions): Unit

{ .api }

interface CreateUnitOptions {
  aliases?: string[]
  prefixes?: string
  offset?: number
  override?: boolean
}
// Create simple unit based on existing unit
createUnit('byte') // Base unit for digital storage
createUnit('kilobyte', '1024 byte')
createUnit('megabyte', '1024 kilobyte') 
createUnit('gigabyte', '1024 megabyte')

// Use new units
const storage = unit('2.5 gigabyte')
to(storage, 'megabyte') // 2560 megabyte
to(storage, 'byte') // 2684354560 byte

// Create unit with aliases
createUnit('dollar', { aliases: ['usd', '$'] })
unit('100 dollar') // 100 dollar
unit('50 usd') // 50 usd (same unit)

// Create derived unit
createUnit('mph', 'mile/hour')
unit('60 mph') // 60 mph
to(unit('60 mph'), 'm/s') // ~26.82 m/s

Advanced Custom Units

// Create unit with offset (like temperature scales)
createUnit('rankine', { definition: '(5/9) kelvin', offset: 0 })
createUnit('reaumur', { definition: '(5/4) celsius', offset: 0 })

// Create unit system
createUnit('furlong', '220 yard')
createUnit('fortnight', '14 day')  
createUnit('speed_unusual', 'furlong/fortnight')

const unusualSpeed = unit('1 furlong/fortnight')
to(unusualSpeed, 'meter/second') // ~0.00000166 m/s

// Create currency units (relative values)
createUnit('euro', '1.1 dollar') // Exchange rate example
createUnit('pound', '1.3 dollar')

const price = unit('100 euro')
to(price, 'dollar') // 110 dollar (using defined rate)

Built-in Unit Categories

Length Units

// Metric
unit('1 mm') // millimeter  
unit('1 cm') // centimeter
unit('1 dm') // decimeter
unit('1 m') // meter
unit('1 km') // kilometer

// Imperial/US
unit('1 inch') // inch
unit('1 ft') // foot  
unit('1 yard') // yard
unit('1 mile') // mile

// Other
unit('1 au') // astronomical unit
unit('1 lightyear') // light year
unit('1 parsec') // parsec
unit('1 angstrom') // angstrom

// Conversions
to(unit('1 inch'), 'cm') // 2.54 cm
to(unit('1 mile'), 'km') // ~1.609 km
to(unit('1 lightyear'), 'm') // ~9.461e15 m

Mass and Weight Units

// Metric mass
unit('1 mg') // milligram
unit('1 g') // gram
unit('1 kg') // kilogram  
unit('1 tonne') // metric ton

// Imperial/US mass  
unit('1 grain') // grain
unit('1 ounce') // ounce
unit('1 lb') // pound
unit('1 ton') // short ton (US)
unit('1 longton') // long ton (UK)

// Other
unit('1 carat') // carat (gemstones)
unit('1 atomicmass') // atomic mass unit
unit('1 electronmass') // electron mass

// Weight (force) units
unit('1 N') // newton
unit('1 lbf') // pound-force
unit('1 kgf') // kilogram-force

// Conversions
to(unit('1 lb'), 'kg') // ~0.453592 kg
to(unit('1 ounce'), 'g') // ~28.3495 g

Time Units

// Basic time
unit('1 ns') // nanosecond
unit('1 microsecond') // microsecond  
unit('1 ms') // millisecond
unit('1 s') // second
unit('1 minute') // minute
unit('1 hour') // hour
unit('1 day') // day
unit('1 week') // week
unit('1 month') // month (30.4375 days)
unit('1 year') // year (365.25 days)

// Specialized
unit('1 decade') // 10 years
unit('1 century') // 100 years  
unit('1 millennium') // 1000 years

// Conversions
to(unit('2 hours'), 'second') // 7200 second
to(unit('30 day'), 'year') // ~0.082 year

Area Units

// Metric area
unit('1 mm^2') // square millimeter
unit('1 cm^2') // square centimeter  
unit('1 m^2') // square meter
unit('1 km^2') // square kilometer
unit('1 hectare') // hectare (10000 m^2)

// Imperial/US area  
unit('1 in^2') // square inch
unit('1 ft^2') // square foot
unit('1 yard^2') // square yard
unit('1 mile^2') // square mile  
unit('1 acre') // acre

// Conversions
to(unit('1 acre'), 'm^2') // ~4047 m^2
to(unit('1 hectare'), 'acre') // ~2.471 acre

Volume Units

// Metric volume
unit('1 mm^3') // cubic millimeter
unit('1 cm^3') // cubic centimeter
unit('1 dm^3') // cubic decimeter  
unit('1 m^3') // cubic meter
unit('1 liter') // liter (dm^3)
unit('1 ml') // milliliter (cm^3)

// Imperial/US volume
unit('1 in^3') // cubic inch
unit('1 ft^3') // cubic foot
unit('1 gallon') // US gallon
unit('1 quart') // US quart
unit('1 pint') // US pint  
unit('1 cup') // US cup
unit('1 floz') // fluid ounce
unit('1 tablespoon') // tablespoon
unit('1 teaspoon') // teaspoon

// UK Imperial
unit('1 gallon_imp') // Imperial gallon
unit('1 pint_imp') // Imperial pint

// Conversions
to(unit('1 gallon'), 'liter') // ~3.785 liter
to(unit('1 liter'), 'gallon') // ~0.264 gallon
to(unit('1 m^3'), 'liter') // 1000 liter

Temperature Units

// Temperature scales
unit('0 celsius') // Celsius  
unit('32 fahrenheit') // Fahrenheit
unit('273.15 kelvin') // Kelvin
unit('491.67 rankine') // Rankine

// Temperature conversions (handle offset scales correctly)
to(unit('0 celsius'), 'fahrenheit') // 32 fahrenheit
to(unit('100 celsius'), 'kelvin') // 373.15 kelvin
to(unit('68 fahrenheit'), 'celsius') // 20 celsius

// Temperature differences (no offset)  
const tempDiff = unit('10 degC') // 10 degree difference
to(tempDiff, 'degF') // 18 degF (difference)

Speed and Velocity Units

// Speed units
unit('1 m/s') // meter per second
unit('1 km/h') // kilometer per hour  
unit('1 mph') // mile per hour
unit('1 ft/s') // foot per second
unit('1 knot') // nautical mile per hour

// Special speeds
unit('1 c') // speed of light
unit('1 mach') // speed of sound (approximate)

// Conversions
to(unit('60 mph'), 'km/h') // ~96.56 km/h
to(unit('100 km/h'), 'm/s') // ~27.78 m/s
to(unit('1 knot'), 'm/s') // ~0.514 m/s

Energy and Power Units

// Energy units
unit('1 J') // joule
unit('1 kJ') // kilojoule  
unit('1 cal') // calorie
unit('1 kcal') // kilocalorie (food calorie)
unit('1 Btu') // British thermal unit
unit('1 kWh') // kilowatt hour
unit('1 eV') // electron volt
unit('1 erg') // erg (CGS)

// Power units  
unit('1 W') // watt
unit('1 kW') // kilowatt
unit('1 MW') // megawatt
unit('1 hp') // horsepower
unit('1 PS') // metric horsepower

// Conversions
to(unit('1 kWh'), 'J') // 3600000 J
to(unit('1 hp'), 'W') // ~745.7 W
to(unit('1 cal'), 'J') // ~4.184 J

Pressure Units

// Pressure units
unit('1 Pa') // pascal
unit('1 kPa') // kilopascal  
unit('1 MPa') // megapascal
unit('1 bar') // bar
unit('1 atm') // atmosphere
unit('1 mmHg') // millimeter mercury
unit('1 psi') // pound per square inch
unit('1 torr') // torr

// Conversions
to(unit('1 atm'), 'Pa') // 101325 Pa
to(unit('1 bar'), 'psi') // ~14.504 psi
to(unit('760 mmHg'), 'atm') // 1 atm

Electrical Units

// Basic electrical units
unit('1 A') // ampere (current)
unit('1 V') // volt (voltage)  
unit('1 ohm') // ohm (resistance)
unit('1 W') // watt (power)
unit('1 F') // farad (capacitance)
unit('1 H') // henry (inductance)
unit('1 C') // coulomb (charge)
unit('1 S') // siemens (conductance)

// Derived units
unit('1 kW') // kilowatt
unit('1 mA') // milliampere
unit('1 kV') // kilovolt  
unit('1 kOhm') // kiloohm
unit('1 uF') // microfarad
unit('1 mH') // millihenry

// Electrical calculations
const i = unit('2 A')
const v = unit('12 V')  
const p = multiply(v, i) // 24 W
const r = divide(v, i) // 6 ohm

Frequency and Angular Units

// Frequency
unit('1 Hz') // hertz
unit('1 kHz') // kilohertz
unit('1 MHz') // megahertz  
unit('1 GHz') // gigahertz
unit('1 rpm') // revolutions per minute

// Angular units
unit('1 rad') // radian
unit('1 deg') // degree  
unit('1 grad') // gradian
unit('1 arcmin') // arc minute
unit('1 arcsec') // arc second
unit('1 revolution') // full rotation

// Conversions
to(unit('180 deg'), 'rad') // π rad
to(unit('1 revolution'), 'deg') // 360 deg
to(unit('60 rpm'), 'Hz') // 1 Hz

Unit Splitting and Formatting

Split Units into Components

splitUnit(unit: Unit, parts: string[]): Unit[]

{ .api }

// Split time into hours, minutes, seconds
const duration = unit('7463 second')
splitUnit(duration, ['hour', 'minute', 'second'])
// [2 hour, 4 minute, 23 second] (2h 4m 23s)

// Split length into feet and inches  
const height = unit('73 inch')  
splitUnit(height, ['ft', 'inch'])
// [6 ft, 1 inch] (6'1")

// Split weight into pounds and ounces
const weight = unit('2.75 lb')
splitUnit(weight, ['lb', 'ounce'])  
// [2 lb, 12 ounce]

// Custom formatting with split units
function formatTime(seconds) {
  const parts = splitUnit(unit(seconds, 'second'), ['hour', 'minute', 'second'])
  return parts.map(part => part.toString()).join(' ')
}
formatTime(3661) // "1 hour 1 minute 1 second"

Physical Constants with Units

Math.js includes many physical constants with proper units:

// Fundamental constants
speedOfLight // ~299792458 m/s
planckConstant // ~6.626e-34 J*s  
electronCharge // ~1.602e-19 C
electronMass // ~9.109e-31 kg
protonMass // ~1.673e-27 kg
avogadro // ~6.022e23 mol^-1
boltzmann // ~1.381e-23 J/K
gravity // 9.80665 m/s^2 (standard)

// Usage in calculations
const energy = multiply(electronMass, pow(speedOfLight, 2))
// E = mc² for electron rest energy

const force = multiply(unit('70 kg'), gravity) // Weight of 70kg person  
to(force, 'lbf') // Convert to pounds-force

Advanced Unit Operations

Unit Validation and Testing

// Check if value has a unit  
isUnit(unit('5 meter')) // true
isUnit(5) // false

// Check if unit has numeric value
hasNumericValue(unit('5 meter')) // true
hasNumericValue(unit('meter')) // false (no numeric part)

// Get unit components
const speed = unit('60 km/h')
speed.value // 60
speed.units // [{ unit: 'm', power: 1 }, { unit: 's', power: -1 }] (SI base)
speed.toString() // "60 km / h"

Unit Compatibility

// Units are compatible if they have the same dimension
function areCompatible(unit1, unit2) {
  try {
    to(unit1, unit2.units)
    return true
  } catch (error) {
    return false  
  }
}

areCompatible(unit('5 meter'), unit('10 foot')) // true (both length)
areCompatible(unit('5 kg'), unit('10 second')) // false (different dimensions)

// Get dimension of unit
function getDimension(unit_val) {
  // Convert to SI base units to see fundamental dimensions  
  return unit_val.to('SI')
}

Working with Dimensionless Units

// Dimensionless quantities
unit('5') // Just number 5
unit('0.5') // 0.5 (could be percentage, ratio, etc.)

// Converting to dimensionless
const ratio = divide(unit('10 meter'), unit('5 meter')) // 2 (dimensionless)

// Angles are dimensionless but have units for clarity
const angle = unit('45 deg')
to(angle, 'rad') // π/4 rad
sin(angle) // sin(45°) = √2/2

Unit System Conversions

Metric (SI) System

// Base SI units: meter, kilogram, second, ampere, kelvin, mole, candela
const siUnits = {
  length: unit('1 m'),
  mass: unit('1 kg'),  
  time: unit('1 s'),
  current: unit('1 A'),
  temperature: unit('1 K'), 
  amount: unit('1 mol'),
  luminosity: unit('1 cd')
}

// Convert measurements to SI
function toSI(measurement) {
  return measurement.to('SI')
}

Imperial/US System

// Common US/Imperial units
const usUnits = {
  length: unit('1 ft'),
  mass: unit('1 lb'),
  volume: unit('1 gallon'),  
  temperature: unit('1 fahrenheit'),
  area: unit('1 acre'),
  speed: unit('1 mph')
}

// Convert between systems
function toMetric(usValue, targetUnit) {
  return to(usValue, targetUnit)
}

toMetric(unit('70 fahrenheit'), 'celsius') // 21.11 celsius
toMetric(unit('60 mph'), 'km/h') // 96.56 km/h

Performance and Memory Considerations

Efficient Unit Operations

// Pre-compile unit conversions for repeated use
const meterToFeet = (meters) => to(unit(meters, 'meter'), 'ft')
const celsiusToFahrenheit = (celsius) => to(unit(celsius, 'celsius'), 'fahrenheit')

// Batch conversions
const distances_m = [100, 200, 300, 500, 1000]
const distances_ft = distances_m.map(meterToFeet)

// Use unit arithmetic instead of converting to numbers
const area_m2 = multiply(unit('10 m'), unit('5 m')) // 50 m^2
const area_ft2 = to(area_m2, 'ft^2') // More accurate than converting first

Working with Large Unit Systems

// For applications with many custom units, create them systematically
function createCurrencySystem(baseCurrency, rates) {
  Object.entries(rates).forEach(([currency, rate]) => {
    createUnit(currency, `${rate} ${baseCurrency}`)
  })
}

createCurrencySystem('USD', {
  EUR: 0.85,
  GBP: 0.73,
  JPY: 110,
  CAD: 1.25
})

// Now can convert between currencies
const price = unit('100 USD')
to(price, 'EUR') // 85 EUR

Common Unit Patterns

Engineering Calculations

// Electrical engineering
function ohmsLaw(voltage, current, resistance) {
  if (voltage && current) return { resistance: divide(voltage, current) }
  if (voltage && resistance) return { current: divide(voltage, resistance) }  
  if (current && resistance) return { voltage: multiply(current, resistance) }
}

const result = ohmsLaw(unit('12 V'), unit('2 A'))
result.resistance // 6 ohm

// Mechanical engineering  
function kineticEnergy(mass, velocity) {
  return multiply(0.5, multiply(mass, pow(velocity, 2)))
}

const ke = kineticEnergy(unit('1000 kg'), unit('25 m/s'))
to(ke, 'kJ') // 312.5 kJ

// Fluid dynamics
function reynoldsNumber(density, velocity, length, viscosity) {
  return divide(multiply(density, multiply(velocity, length)), viscosity)
}

Scientific Applications

// Chemistry: ideal gas law PV = nRT
function idealGas(pressure, volume, moles, temperature) {
  const R = unit('8.314 J/(mol*K)') // Gas constant
  
  if (!pressure) return divide(multiply(moles, multiply(R, temperature)), volume)
  if (!volume) return divide(multiply(moles, multiply(R, temperature)), pressure)
  if (!moles) return divide(multiply(pressure, volume), multiply(R, temperature))
  if (!temperature) return divide(multiply(pressure, volume), multiply(moles, R))
}

// Physics: wavelength-frequency relationship  
function wavelengthFrequency(wavelength, frequency) {
  if (wavelength) return divide(speedOfLight, wavelength)
  if (frequency) return divide(speedOfLight, frequency)
}

const freq = wavelengthFrequency(unit('500 nm')) // Green light frequency
to(freq, 'THz') // ~600 THz

Everyday Calculations

// Cooking conversions
function convertRecipe(ingredient, targetUnit) {
  return to(ingredient, targetUnit)  
}

convertRecipe(unit('2 cup'), 'ml') // ~473 ml
convertRecipe(unit('350 fahrenheit'), 'celsius') // ~177 celsius

// Travel calculations  
function travelTime(distance, speed) {
  return divide(distance, speed)
}

const time = travelTime(unit('300 km'), unit('80 km/h'))
to(time, 'hour') // 3.75 hour = 3h 45m

// Fuel efficiency
function fuelConsumption(distance, fuel) {
  return divide(distance, fuel)
}

const efficiency = fuelConsumption(unit('400 mile'), unit('12 gallon'))
to(efficiency, 'km/l') // ~14.1 km/l

Error Handling with Units

import { DimensionError } from 'mathjs'

try {
  // Incompatible unit operations
  add(unit('5 meter'), unit('3 second')) // DimensionError
} catch (error) {
  if (error instanceof DimensionError) {
    console.log('Cannot add different unit dimensions')  
  }
}

try {
  // Invalid unit conversion
  to(unit('5 kg'), 'meter') // DimensionError
} catch (error) {
  console.log('Cannot convert mass to length')
}

// Safe unit operations
function safeAdd(unit1, unit2) {
  try {
    return add(unit1, unit2)
  } catch (error) {
    return null // or throw custom error
  }
}

function safeConvert(value, targetUnit) {
  try {
    return to(value, targetUnit)  
  } catch (error) {
    return value // Return original if conversion fails
  }
}

Chain Operations with Units

// Units work seamlessly with chain operations
const result = chain(unit('100 mile'))
  .to('km')        // Convert to kilometers  
  .multiply(2)     // Double the distance
  .divide(unit('80 km/h')) // Divide by speed to get time
  .to('hour')      // Convert to hours
  .done()          // ~5 hours

// Complex unit calculations in chain
const power = chain(unit('12 V'))
  .multiply(unit('5 A'))  // 60 W
  .multiply(unit('2 hour')) // 120 Wh  
  .to('kWh')              // 0.12 kWh
  .done()

Install with Tessl CLI

npx tessl i tessl/npm-mathjs

docs

arithmetic.md

data-types.md

expressions.md

index.md

matrices.md

probability.md

statistics.md

trigonometry.md

units.md

tile.json