RepoPilot

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

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

Question

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

RepoPilot

The prettyBytes function formats byte counts into human-readable strings through a multi-step process [index.js:L124-L179]:

1. Input Validation & Options Setup The function first validates that the input is a finite number or bigint [index.js:L125-L127]. It then merges user options with defaults, setting bits, binary, space, and nonBreakingSpace [index.js:L129-L134].

2. Unit Selection Based on the options, the function selects the appropriate unit array [index.js:L136-L139]:

  • BYTE_UNITS (default): 'B', 'kB', 'MB', 'GB', etc. [index.js:L1-L9]
  • BIBYTE_UNITS: 'B', 'KiB', 'MiB', 'GiB', etc. for binary format [index.js:L11-L19]
  • BIT_UNITS: 'b', 'kbit', 'Mbit', 'Gbit', etc. for bits [index.js:L21-L29]
  • BIBIT_UNITS: 'b', 'kibit', 'Mibit', 'Gibit', etc. for binary bits [index.js:L31-L39]

3. Sign Handling For negative numbers, it extracts the sign prefix and converts to positive for processing [index.js:L147-L150]. It also handles the signed zero case specially [index.js:L141-L145].

4. Exponent Calculation For numbers ≥ 1, it calculates the appropriate exponent (which unit to use) using either base-1024 (binary) or base-1000 (SI prefix) [index.js:L158].

5. Formatting & Localization The number is scaled by dividing by 1000^exponent (or 1024^exponent for binary) [index.js:L159]. If no locale is specified, precision is adjusted to maintain significant digits [index.js:L161-L163]. The number is then formatted as a locale string if a locale is provided [index.js:L165].

6. Assembly & Padding Finally, it combines the prefix, formatted number, separator (space or non-breaking space), and unit into the result [index.js:L166-L167]. If fixedWidth is specified, padding is applied for alignment [index.js:L169].

Example: prettyBytes(1337) yields '1.34 kB' because 1337 ÷ 1000 ≈ 1.34, formatted with the 'kB' unit.

FOLLOW_UPS:

  • What options does prettyBytes support?
  • How does the binary option differ from default behavior?
  • How does locale formatting work in prettyBytes?

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.