RepoPilot

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

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

Question

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

RepoPilot

The pretty-bytes library converts byte counts into human-readable strings by using a logarithmic approach to determine the appropriate unit (B, kB, MB, GB, etc.), then formatting the number with that unit.

Core Formatting Process

The main logic is in [index.js:L124-L179]. Here's how it works:

  1. Input Validation: It first checks that the input is a finite number or bigint [index.js:L125-L127].

  2. Unit Selection: It uses Math.floor() and either log10() or natural logarithm to determine which unit to apply. For base-10 (default), it divides the logarithm by 3 to find the exponent [index.js:L158]:

    const exponent = Math.min(Math.floor(options.binary ? log(number) / Math.log(1024) : log10(number) / 3), UNITS.length - 1);
    
  3. Scaling: Once the exponent is determined, the number is scaled down by dividing by either 1000 (base-10) or 1024 (binary) raised to the power of the exponent [index.js:L159].

  4. Precision Handling: By default, it uses 3 significant digits [index.js:L162-L164]. If minimumFractionDigits or maximumFractionDigits options are set, values are truncated instead of rounded [index.d.ts:L52-L53].

  5. Localization & Formatting: The number is converted to a locale-specific string and combined with the unit and separator [index.js:L167-L168].

Example

For input 1337, the library calculates it falls into the kilobyte range, scales it to 1.34, and outputs '1.34 kB' [readme.md:L3].

The library supports multiple formatting options including bits, binary, signed, space, and locale to customize the output format.

FOLLOW_UPS:

  • What options control the output formatting?
  • How does the binary vs. SI prefix option differ?
  • Can you explain the signed option behavior?

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.