Format byte counts as readable sizes

JavaScript
// Format a byte count using binary units by default (1 KB = 1024 bytes).
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];

function formatBytes(bytes, { decimals = 1, binary = true } = {}) {
  if (!Number.isFinite(bytes) || bytes < 0) throw new RangeError('bytes must be >= 0');
  const base = binary ? 1024 : 1000;
  const units = binary ? UNITS : ['B', 'kB', 'MB', 'GB', 'TB', 'PB'];
  let value = bytes;
  let unit = 0;
  while (value >= base && unit < units.length - 1) {
    value /= base;
    unit += 1;
  }
  const digits = unit === 0 ? 0 : decimals;
  return `${value.toFixed(digits)} ${units[unit]}`;
}

console.log(formatBytes(0)); // 0 B
console.log(formatBytes(1536)); // 1.5 KB
console.log(formatBytes(15_000_000, { binary: false })); // 15.0 MB