Skip to content
jshacks.dev
Fundamentals

Format bytes as human-readable sizes

Format a byte count as a human-readable size, with a loop over binary units, and see where Intl.NumberFormat with the unit style differs. Node.js 18.

2 min read
Summarize in AI

Showing 1536 as 1.5 KiB takes a logarithm, a unit table and a rounding step. The function below ran on Node.js 24, and one line of its output shows where the built-in unit formatter disagrees with it.

JavaScript
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];

function formatBytes(bytes, digits = 1) {
  if (bytes === 0) return '0 B';
  const power = Math.min(Math.floor(Math.log(Math.abs(bytes)) / Math.log(1024)), units.length - 1);
  const value = bytes / 1024 ** power;
  return `${Number.parseFloat(value.toFixed(digits))} ${units[power]}`;
}

console.log([0, 1023, 1024, 1536, 5_242_880, 1_073_741_824, 2 ** 50].map((n) => formatBytes(n)));
console.log(new Intl.NumberFormat('en', { style: 'unit', unit: 'megabyte', maximumFractionDigits: 1 }).format(5.24288));
Text
[
  '0 B',      '1023 B',
  '1 KiB',    '1.5 KiB',
  '5 MiB',    '1 GiB',
  '1024 TiB'
]
5.2 MB

The power is floor(log(bytes) / log(1024)), capped at the last unit, so 1_073_741_824 becomes 1 GiB. parseFloat(value.toFixed(1)) trims the trailing zero, and 1024 prints 1 KiB and not 1.0 KiB. The last line uses Intl.NumberFormat with style: 'unit' and unit: 'megabyte', which formats a number with a localized unit name but does no conversion and counts in the units it is given, so 5.24288 prints 5.2 MB and it does not know that 5,242,880 bytes is 5 MiB. The unit identifiers are in the ECMA-402 specification for Intl.NumberFormat.

Pick one convention. KiB, MiB and GiB mean multiples of 1,024. The SI kB, MB and GB mean multiples of 1,000, and mixing them gives sizes that differ by about 7 percent at the gigabyte level. Operating systems disagree too, so say which one you use in the interface.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.