How does pretty-bytes format byte counts into a human-readable string?
How does pretty-bytes format byte counts into a human-readable string?
About sindresorhus/pretty-bytes · 2 messages · last activity 7/13/2026
The pretty-bytes library formats byte counts using a multi-step process implemented in the main prettyBytes function [index.js:L124-L179]:
Core Logic:
-
Input Validation: The function first checks that the input is a finite number or bigint, throwing a TypeError if not [index.js:L125-L127].
-
Unit Selection: It selects the appropriate unit system based on options:
bitsoption: uses BIT_UNITS or BIBIT_UNITSbinaryoption: uses BIBYTE_UNITS or BYTE_UNITS (default is decimal SI prefix) [index.js:L140-L142]
-
Exponent Calculation: For numbers ≥ 1, it calculates which unit tier to use by computing the exponent. For binary format, it uses
log(number) / Math.log(1024), while decimal format useslog10(number) / 3. The result is clamped to the maximum available unit [index.js:L159]. -
Number Scaling: The number is divided by either 1024^exponent (binary) or 1000^exponent (decimal) to scale it appropriately [index.js:L160].
-
Localization & Formatting: If no locale is specified, it applies precision formatting; otherwise, it uses
toLocaleString()with locale-specific options [index.js:L162-L168]. -
Output Assembly: The result combines a prefix (for signed numbers), the formatted number, a separator (space or non-breaking space), and the unit [index.js:L170].
Example: prettyBytes(1337) returns '1.34 kB' because 1337 bytes falls into the kilobyte range and is formatted with appropriate precision.
The function also handles edge cases like negative numbers, zero, numbers less than 1, and extremely large values exceeding exabytes [index.js:L147-L158].
FOLLOW_UPS:
- What options can customize the formatting behavior?
- How does the function handle bigint inputs differently?
- What's the difference between binary and decimal formatting?
Want to ask your own question?
Open chat for sindresorhus/pretty-bytesPublic 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.