RepoPilot

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

About sindresorhus/pretty-bytes · 2 messages · last activity 5/25/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 by determining the appropriate unit (B, kB, MB, GB, etc.) and then scaling the number accordingly.

Core Formatting Process

The main function [index.js:L124-L179] implements the following logic:

  1. Input Validation: It first checks that the input is a valid finite number or bigint.

  2. Unit Selection: Based on the options provided (bits, binary), it selects from one of four unit arrays [index.js:L1-L42]:

    • BYTE_UNITS: Standard byte units (B, kB, MB, GB, TB, PB, EB, ZB, YB)
    • BIBYTE_UNITS: Binary byte units (B, KiB, MiB, GiB, TiB, PiB, EiB, ZiB, YiB)
    • BIT_UNITS: Standard bit units (b, kbit, Mbit, Gbit, etc.)
    • BIBIT_UNITS: Binary bit units (b, kibit, Mibit, Gibit, etc.)
  3. Exponent Calculation: For numbers ≥ 1, it calculates which unit level to use via the exponent, using either base-10 (1000) or base-2 (1024) depending on the binary option [index.js:L160].

  4. Number Scaling: The original number is divided by the appropriate power (1000^exponent or 1024^exponent) to get a manageable decimal value.

  5. Localization: The scaled number is formatted using toLocaleString() if a locale option is specified, otherwise precision is adjusted to show meaningful digits.

  6. Assembly: The result combines the prefix (sign), formatted number, optional separator (space or non-breaking space), and unit string.

For example, 1337 bytes becomes 1.34 kB because 1337 ÷ 1000¹ = 1.337, which is formatted as 1.34 with the kB unit.

FOLLOW_UPS:

  • What options can customize the formatting behavior?
  • How does the binary option differ from standard formatting?
  • What happens with numbers smaller than 1?

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.