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/6/2026
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:
-
Input Validation: It first checks that the input is a finite number or bigint [index.js:L125-L127].
-
Unit Selection: It uses
Math.floor()and eitherlog10()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); -
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].
-
Precision Handling: By default, it uses 3 significant digits [index.js:L162-L164]. If
minimumFractionDigitsormaximumFractionDigitsoptions are set, values are truncated instead of rounded [index.d.ts:L52-L53]. -
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-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.