Format a byte count for humans
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".
What it has to do
- Use 1024 as the step between
B,KB,MB,GBandTB. - Pick the largest unit for which the value is still at least 1.
- Round to
decimalsdecimal 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.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.