javascript 28 lines · 8 steps

Formatting byte counts into human units

A function that scales a raw byte count into the right unit with a logarithm and formats it cleanly.

Explained by highlit
1const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
2 
3export function formatBytes(bytes, { decimals = 1, binary = false } = {}) {
4 if (!Number.isFinite(bytes)) {
5 throw new TypeError('bytes must be a finite number');
6 }
7 
8 const sign = bytes < 0 ? '-' : '';
9 let value = Math.abs(bytes);
10 
11 if (value < 1) {
12 return `${sign}${value} B`;
13 }
14 
15 const base = binary ? 1024 : 1000;
16 const exponent = Math.min(
17 Math.floor(Math.log(value) / Math.log(base)),
18 UNITS.length - 1
19 );
20 
21 value /= base ** exponent;
22 
23 const rounded = value.toFixed(exponent === 0 ? 0 : decimals);
24 const unit = UNITS[exponent];
25 const suffix = binary && exponent > 0 ? unit.replace('B', 'iB') : unit;
26 
27 return `${sign}${parseFloat(rounded)} ${suffix}`;
28}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A base-N logarithm tells you which unit a value falls into without a loop or lookup chain.
  2. 2Clamping the exponent to the units array length guards against overflowing past the largest known unit.
  3. 3Splitting off the sign early lets the rest of the math work on a clean positive magnitude.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Formatting byte counts into human units — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code