Skip to content

Data Unit Converter — TypeScript source

Convert between digital data units - B, KB/KiB, MB/MiB, GB/GiB, TB/TiB. Switch between decimal (1000) and binary (1024) bases, runs entirely in your browser.

This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Pure digital-data unit conversion. B, KB/KiB, MB/MiB, GB/GiB, TB/TiB.
// Decimal base = 1000 (KB, MB, GB, TB); binary base = 1024 (KiB, MiB, GiB, TiB).
// Pure + deterministic - the unit-test surface for the Data Unit Converter.
// Never throws: non-finite values or unknown units yield NaN.

export type DataBase = 1000 | 1024;
export type DataUnit = 'B' | 'KB' | 'MB' | 'GB' | 'TB' | 'KiB' | 'MiB' | 'GiB' | 'TiB';

/** Units available under each base, ordered from smallest (B) to largest. */
export const UNITS: Record<DataBase, DataUnit[]> = {
  1000: ['B', 'KB', 'MB', 'GB', 'TB'],
  1024: ['B', 'KiB', 'MiB', 'GiB', 'TiB'],
};

// Power-of-base rank for each unit: B is rank 0, each prefix steps by 1.
const EXPONENT: Record<DataUnit, number> = {
  B: 0,
  KB: 1, MB: 2, GB: 3, TB: 4,
  KiB: 1, MiB: 2, GiB: 3, TiB: 4,
};

/**
 * Convert a value between two digital-data units under the given base.
 * bytes = value × base^exp(fromUnit); result = bytes / base^exp(toUnit).
 * Returns NaN for non-finite input, unknown units, or an invalid base - never throws.
 */
export function convertData(
  value: number,
  fromUnit: DataUnit,
  toUnit: DataUnit,
  base: DataBase,
): number {
  if (!Number.isFinite(value)) return NaN;
  if (base !== 1000 && base !== 1024) return NaN;
  const fromExp = EXPONENT[fromUnit];
  const toExp = EXPONENT[toUnit];
  if (fromExp === undefined || toExp === undefined) return NaN;
  return (value * base ** fromExp) / base ** toExp;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →