Skip to the code
cf.

Format bytes

Write formatBytes(bytes, decimals = 1). It turns a size in bytes (a whole number, 0 or more) into a short label like 1.5 KB.

The units are B, KB, MB, GB, TB, and PB, and each is 1024 times the one before: 1 KB is 1024 bytes, and 1 MB is 1024 KB. Use the largest unit in which the size is at least 1, but never go past PB.

Round to decimals decimal places, with halves rounding up, then drop trailing zeros and a trailing point: 1.50 shows as 1.5, and 2.0 as 2. If rounding reaches 1024 and there's a larger unit, use the larger unit instead: 1048575 bytes is 1023.999 KB, which rounds to 1024.0 KB at one decimal, so it shows as 1 MB.

Put one space between the number and the unit.

formatBytes(512);        // "512 B"
formatBytes(1536);       // "1.5 KB"
formatBytes(2048);       // "2 KB"
formatBytes(1234567, 2); // "1.18 MB"
formatBytes(1048575);    // "1 MB"

What the tests check

  1. shows sizes under 1024 in bytes
    expect(formatBytes(0)).toBe("0 B");
    expect(formatBytes(1)).toBe("1 B");
    expect(formatBytes(1000)).toBe("1000 B");
    expect(formatBytes(1023)).toBe("1023 B");
    
  2. uses 1024 per unit
    expect(formatBytes(1024)).toBe("1 KB");
    expect(formatBytes(1024 ** 2)).toBe("1 MB");
    expect(formatBytes(5 * 1024 ** 3)).toBe("5 GB");
    expect(formatBytes(1024 ** 4)).toBe("1 TB");
    
  3. rounds to one decimal by default
    expect(formatBytes(1536)).toBe("1.5 KB");
    expect(formatBytes(1100)).toBe("1.1 KB");
    expect(formatBytes(123456789)).toBe("117.7 MB");
    
  4. drops trailing zeros
    expect(formatBytes(2048)).toBe("2 KB");
    expect(formatBytes(2048, 2)).toBe("2 KB");
    expect(formatBytes(1536, 3)).toBe("1.5 KB");
    expect(formatBytes(1280, 2)).toBe("1.25 KB");
    
  5. rounds to the given number of decimals
    expect(formatBytes(1234567, 2)).toBe("1.18 MB");
    expect(formatBytes(1234567, 0)).toBe("1 MB");
    expect(formatBytes(1536, 0)).toBe("2 KB");
    
  6. moves up a unit when rounding reaches 1024
    expect(formatBytes(1048575)).toBe("1 MB");
    expect(formatBytes(1024 ** 3 - 1)).toBe("1 GB");
    expect(formatBytes(1048575, 3)).toBe("1023.999 KB");
    
  7. stops at PB
    expect(formatBytes(1024 ** 5)).toBe("1 PB");
    expect(formatBytes(1024 ** 6)).toBe("1024 PB");
    expect(formatBytes(2 * 1024 ** 6)).toBe("2048 PB");
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).