RepoPilot

How does pretty-bytes format byte counts into a human-readable string?

About sindresorhus/pretty-bytes · 2 messages · last activity 6/29/2026

Question

How does pretty-bytes format byte counts into a human-readable string?

RepoPilot

The prettyBytes function converts byte counts to human-readable strings through a multi-step process:

Unit Selection

The function first selects which unit system to use based on options [index.js:L139-L142]:

  • bits option: Uses BIT_UNITS (b, kbit, Mbit, ...) or BIBIT_UNITS (b, kibit, Mibit, ...)
  • binary option: Uses binary prefixes (KiB, MiB, GiB, ...) with base-1024, or SI prefixes (kB, MB, GB, ...) with base-1000

The unit arrays are defined in [index.js:L1-L37].

Exponent Calculation

For numbers ≥ 1, the function calculates an exponent to determine the appropriate scale [index.js:L157]:

  • For binary: Math.floor(log(number) / Math.log(1024))
  • For decimal: Math.floor(log10(number) / 3)

This exponent selects which unit from the array to use (0 = bytes, 1 = kilobytes, 2 = megabytes, etc.).

Number Scaling and Formatting

The number is then divided by the appropriate power [index.js:L158]:

  • Binary: 1024 ** exponent
  • Decimal: 1000 ** exponent

For non-localized output, precision is applied [index.js:L160-L162], and the number is converted to a locale string using toLocaleString [index.js:L163].

Result Assembly

Finally, the function combines [index.js:L164-L165]:

  • Optional sign prefix ('+', '-', or ' ')
  • Formatted number
  • Separator (space by default)
  • Unit string

The result is padded to a fixed width if specified via applyFixedWidth [index.js:L166].

FOLLOW_UPS:

  • What localization options does pretty-bytes support?
  • How does pretty-bytes handle very large numbers?
  • What's the difference between binary and SI prefixes?

Want to ask your own question?

Open chat for sindresorhus/pretty-bytes

Public Q&A. Generated by RepoPilot from the actual source of sindresorhus/pretty-bytes. AI answers can be incomplete or stale — verify before relying on them.