Skip to content
GreenSnippets

Format bytes as KB, MB, GB

Convert a byte count into a short human-readable size such as 1.5 MB.

JavaScript
function formatBytes(bytes, decimals = 1) {
  if (!Number.isFinite(bytes) || bytes < 0) throw new RangeError("bytes must be a non-negative number");
  if (bytes === 0) return "0 B";
  const units = ["B", "KB", "MB", "GB", "TB", "PB"];
  const i = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
  const value = bytes / 1024 ** i;
  return `${Number(value.toFixed(decimals))} ${units[i]}`;
}

Example / expected output

Output
formatBytes(1536)      // "1.5 KB"
formatBytes(5_000_000) // "4.8 MB"

How it works

Uses base-1024 steps with the common KB/MB/GB labels. The number of decimals is configurable and trailing zeros are dropped. Negative or non-finite input throws instead of returning nonsense.