Skip to content
38

formatBytes

Human-readable file sizes in binary steps, such as 1.5 KB or 12.0 MB, for upload lists and storage meters.

Example

Installation

npx shadcn@latest add https://hirael.com/r/format-bytes.json

Usage

import { formatBytes } from "@/lib/format-bytes"

Paths assume the default @/ alias from your components.json.

API

formatBytes()

ParameterTypeDefault
bytes*

Size in bytes. Negative or non-finite input reads as `0 B`.

numbernone
Returnsstring

Source

const UNITS = ['B', 'KB', 'MB', 'GB', 'TB'] as const;

/**
 * Human file size in binary steps: `1536` → `1.5 KB`.
 * @param bytes Size in bytes. Negative or non-finite input reads as `0 B`.
 */
export const formatBytes = (bytes: number): string => {
  if (!Number.isFinite(bytes) || bytes < 0) return '0 B';
  let i = 0;
  let n = bytes;
  while (n >= 1024 && i < UNITS.length - 1) {
    n /= 1024;
    i++;
  }
  // Rounding can carry up to 1024 (1048575 B is "1024.0 KB"), so step up once more.
  if (Number(n.toFixed(i === 0 ? 0 : 1)) >= 1024 && i < UNITS.length - 1) {
    n /= 1024;
    i++;
  }

  return `${i === 0 ? n.toFixed(0) : n.toFixed(1)} ${UNITS[i]}`;
};

Shipped