Scriptdrill

Level 3: Strings and dates Exercise 41 of 76 Free

Human readable file size

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Format a byte count `n` (a non-negative integer) for people. The units are `B`, `KB`, `MB`, `GB` and `TB`, each 1024 times the previous one. Pick the largest unit in which the value is at least 1, choosing the unit before any rounding. Plain bytes are shown without decimals (`"512 B"`, `"0 B"`); every other unit shows exactly one decimal (`"1.5 KB"`, `"1.0 MB"`). Values of 1024 TB and more stay in TB (`"2048.0 TB"`).

What this exercise teaches

Choosing the unit by repeated division, then formatting, keeps the unit and the number consistent. Using 1000 instead of 1024 happens to give the same strings for round numbers like 1536 and 1048576, which is why the hidden tests use 1023 and 1024.

A hint if you get stuck

Divide by 1024 while the value is at least 1024 and you have not reached TB, counting the steps. Then `toFixed(1)` for any unit above bytes.

Try it now, free, no account needed

Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Strings and dates