RepoPilot

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

About sindresorhus/pretty-bytes · 2 messages · last activity 5/18/2026

Question

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

RepoPilot

The pretty-bytes library converts byte counts to human-readable strings through a multi-step process implemented in the main function [index.js:L124-L179]:

Core Logic

  1. Input Validation: First, it validates that the input is a finite number or bigint [index.js:L125-L127].

  2. Unit Selection: Based on the options provided, it selects the appropriate unit system:

    • Bytes by default (BYTE_UNITS: B, kB, MB, GB, TB, PB, EB, ZB, YB) [index.js:L1-L9]
    • Bits if bits: true (BIT_UNITS: b, kbit, Mbit, Gbit, etc.)
    • Binary prefixes if binary: true (BIBYTE_UNITS: B, KiB, MiB, GiB, etc.) [index.js:L14-L22]
    • Binary bits if both bits: true and binary: true (BIBIT_UNITS: b, kibit, Mibit, etc.) [index.js:L27-L35]
  3. Exponent Calculation: For numbers ≥ 1, it calculates which unit to use by determining the exponent. For decimal (base-10), it divides by 1000 each step; for binary (base-2), it divides by 1024 [index.js:L158].

  4. Number Formatting: The formatted number is divided by the appropriate power (1000^n or 1024^n), then converted to a string with proper precision. If a locale is specified, toLocaleString is used for localization [index.js:L160-L164].

  5. Final Assembly: The result combines the formatted number, an optional separator (space or non-breaking space), and the selected unit [index.js:L165].

For example, 1337 becomes 1.34 kB by dividing by 1000 once and appending the "kB" unit.

FOLLOW_UPS:

  • What options can you pass to customize formatting?
  • How does the signed option work for showing differences?
  • What is the difference between binary and decimal formatting?

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.