AniUI Academy

Format a byte count for humans

easyDOM & Utilities+150 XPPractice

A file input hands you a byte count and nobody wants to read 1348576. Bundle analysers, upload progress bars and storage meters all need the same conversion.

Implement formatBytes(bytes, decimals = 1) where bytes is a non-negative number. The units are B, KB, MB, GB and TB, each step 1024 times the previous one. Divide by 1024 repeatedly while the value is at least 1024 and a larger unit is still available, so 1024 lands on 1 KB rather than 1024 B.

Format the result as the number, then one space, then the unit. The number is rounded to decimals decimal places and trailing zeros are removed, so 1024 with the default gives "1 KB", not "1.0 KB". A value of 0 returns exactly "0 B".

Arguments

bytesnumber
A non-negative byte count to format.
decimalsnumber
Maximum fraction digits to show. Trailing zeros are stripped. Defaults to 1.

Returns

string — The value and unit separated by a single space, picking the largest unit for which the value is still at least 1.

Examples

formatBytes(1024);
// => "1 KB"

A clean unit boundary drops the trailing .0.

formatBytes(1536);
// => "1.5 KB"

Default is one decimal place.

formatBytes(1234567, 2);
// => "1.18 MB"

A custom precision rounds to that many decimals.

What it has to do

  • Use 1024 as the step between B, KB, MB, GB and TB.
  • Pick the largest unit for which the value is still at least 1.
  • Round to decimals decimal places, defaulting to 1, and drop trailing zeros.
  • Separate the number and the unit with exactly one space.
  • Return "0 B" for an input of 0.

Notes

  • This uses binary units (1024-based) with the IEC-ambiguous KB/MB labels — the labels users expect from Finder and most file explorers. Decimal units (KiB, 1000-based) are a different problem.
  • parseFloat(value.toFixed(decimals)) is the neat trick that both rounds and strips trailing zeros in one go — no manual regex needed.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.