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 5/25/2026
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:
-
Input Validation: It first checks that the input is a valid finite number or bigint.
-
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.)
-
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
binaryoption [index.js:L160]. -
Number Scaling: The original number is divided by the appropriate power (1000^exponent or 1024^exponent) to get a manageable decimal value.
-
Localization: The scaled number is formatted using
toLocaleString()if a locale option is specified, otherwise precision is adjusted to show meaningful digits. -
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.