Format Byte Counts With IEC Units

Turn raw byte counts into readable IEC or SI strings with configurable decimals, spacing and correct handling of zero and negatives.

JavascriptCli Tooling

Code

javascriptsnippet
29 lines
const IEC_UNITS = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
const SI_UNITS = ["B", "kB", "MB", "GB", "TB", "PB", "EB"];

export function formatBytes(bytes, options = {}) {
  if (typeof bytes !== "number" || !Number.isFinite(bytes)) {
    throw new TypeError("bytes must be a finite number");
  }
  const { decimals = 1, base = 1024, space = true } = options;
  if (base !== 1000 && base !== 1024) throw new RangeError("base must be 1000 or 1024");
  if (!Number.isInteger(decimals) || decimals < 0 || decimals > 6) {
    throw new RangeError("decimals must be an integer between 0 and 6");
  }
  const units = base === 1024 ? IEC_UNITS : SI_UNITS;
  const sign = bytes < 0 ? "-" : "";
  let value = Math.abs(bytes);
  let unitIndex = 0;
  while (value >= base && unitIndex < units.length - 1) {
    value /= base;
    unitIndex += 1;
  }
  const fixed = value.toFixed(unitIndex === 0 ? 0 : decimals);
  return `${sign}${fixed}${space ? " " : ""}${units[unitIndex]}`;
}

console.log(formatBytes(0));
console.log(formatBytes(1536));
console.log(formatBytes(1048576));
console.log(formatBytes(1500, { base: 1000, decimals: 2, space: false }));
console.log(formatBytes(-2048, { decimals: 0 }));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

0 B
1.5 KiB
1.0 MiB
1.50kB
-2 KiB

Inside the snippet

The code’s whole job belongs to the function formatBytes.

Iteration happens inside while (value >= base && unitIndex < units.length - 1) — everything outside it runs once. Invalid states are rejected up front: it throws TypeError and RangeError instead of continuing with bad data.

What to watch for

  • The guard base !== 1000 && base !== 1024 short-circuits the flow with an early throw when its condition holds.

Using it

The entry-point signature is export function formatBytes(bytes, options = {})

formatBytes is the public entry point; everything else in the file exists to support it.

Key statements

if (base !== 1000 && base !== 1024) throw new RangeError("base must be 1000 or 1024");
throw new RangeError("decimals must be an integer between 0 and 6");
return `${sign}${fixed}${space ? " " : ""}${units[unitIndex]}`;

Interactive Tools for This Topic

FAQ

What happens if the preconditions do not hold?
Validation comes first — `TypeError` and `RangeError` marks the failure at `base !== 1000 && base !== 1024`, before any partial work happens.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `formatBytes` at load time.