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 6/1/2026
The prettyBytes function converts byte counts into human-readable strings by using a multi-step process:
Unit Selection
First, the function selects the appropriate unit array based on the options provided [index.js:L138-L140]:
- Bytes (default): Uses
BYTE_UNITS(B, kB, MB, GB, TB, PB, EB, ZB, YB) with base-10 (1000) - Bits: Uses
BIT_UNITS(b, kbit, Mbit, etc.) with base-10 - Binary Bytes: Uses
BIBYTE_UNITS(B, KiB, MiB, GiB, etc.) with base-2 (1024) - Binary Bits: Uses
BIBIT_UNITS(b, kibit, Mibit, etc.) with base-2
Exponent Calculation
The function determines which unit to use by calculating an exponent [index.js:L161-L162]:
- For decimal:
Math.floor(log10(number) / 3) - For binary:
Math.floor(log(number) / Math.log(1024))
This exponent corresponds to the index in the unit array.
Number Formatting
The number is then divided by the appropriate power (1000 or 1024) and formatted with precision [index.js:L163-L168]. If no locale is specified, precision is calculated to show at least 3 significant figures.
Result Assembly
Finally, the result is assembled by combining the prefix (for signed numbers), the formatted number, an optional separator (space or non-breaking space), and the appropriate unit [index.js:L170-L171].
For example, 1337 becomes 1.34 kB because 1337 ÷ 1000 = 1.34, and the unit at exponent 1 is kB.
FOLLOW_UPS:
- What unit arrays are available for different formats?
- How does the signed option work in prettyBytes?
- How is locale-based number formatting handled?
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.