JavaScript

Format File Size

by @admin
12h ago
Apr 28, 2026
Public
Converts a raw byte count into a human-readable string with the appropriate unit (B, KB, MB, GB, TB). Uses 1024-based (binary) units by default or optionally 1000-based (SI) units. Useful for upload progress indicators, file browsers, and storage dashboards.
JavaScript
function formatBytes(bytes, decimals = 2, binary = true) {
  if (bytes === 0) return '0 B';
  const base  = binary ? 1024 : 1000;
  const units = binary
    ? ['B', 'KiB', 'MiB', 'GiB', 'TiB']
    : ['B', 'KB',  'MB',  'GB',  'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(base));
  return `${parseFloat((bytes / base ** i).toFixed(decimals))} ${units[i]}`;
}

// Usage
console.log(formatBytes(0));           // 0 B
console.log(formatBytes(1024));        // 1 KiB
console.log(formatBytes(1_500_000));   // 1.43 MiB
console.log(formatBytes(1_500_000, 2, false)); // 1.5 MB
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.