X Enterprises
fastify-xconfig

xFormatBytes(bytes, decimals?)

Formats a byte count into a human-readable string like "1.5 MB".

xFormatBytes(bytes, decimals?)

Converts a raw byte count to a human-readable string using 1024-based units (Bytes, KB, MB, GB, TB, PB). The decimal precision defaults to 2.

Signature

fastify.xFormatBytes(bytes: number, decimals?: number): string

Params

NameTypeRequiredDefaultDescription
bytesnumberYesThe byte count to format
decimalsnumberNo2Number of decimal places; values below 0 are treated as 0

Returns

string — human-readable size (e.g. "1.5 MB", "0 Bytes", "512 KB").

Throws

Never throws.

Examples

Basic formatting

fastify.xFormatBytes(0);             // "0 Bytes"
fastify.xFormatBytes(1024);          // "1 KB"
fastify.xFormatBytes(1048576);       // "1 MB"
fastify.xFormatBytes(1073741824);    // "1 GB"
fastify.xFormatBytes(1536, 1);       // "1.5 KB"
fastify.xFormatBytes(1536, 0);       // "2 KB"

Include in API responses

fastify.get("/storage/usage", async (request) => {
  const { usedBytes, totalBytes } = await getStorageUsage();

  return {
    used: fastify.xFormatBytes(usedBytes),
    total: fastify.xFormatBytes(totalBytes),
    usedRaw: usedBytes,
  };
  // { used: "3.2 GB", total: "50 GB", usedRaw: 3435973836 }
});

See also

AI Context

package: "@xenterprises/fastify-xconfig"
method: fastify.xFormatBytes(bytes, decimals?)
use-when: Format a raw byte count to a human-readable string (e.g. 1048576 → "1 MB")
returns: string
Copyright © 2026