Convert bytes to KB, MB and GB in JavaScript
Intermediate · 4 min read
File managers, upload forms and download pages never show "1536000 bytes". They show "1.5 MB". Turning a raw byte count into a size a person can read is a small function that almost every app with files needs.
In this tutorial you will write human(bytes), which picks the right unit (B, KB, MB, GB or TB) and rounds to one decimal place. Then you will find out why a 1 GB memory card shows up as 953.7 MB on your computer. You need to know what an array is, how a while loop works, and what toFixed does.
How the units step up
A byte is the basic unit of computer storage. Bigger units are made by grouping bytes, and in most operating systems each step is 1,024 times the last:
- 1 KB (kilobyte) = 1,024 bytes
- 1 MB (megabyte) = 1,024 KB
- 1 GB (gigabyte) = 1,024 MB
- 1 TB (terabyte) = 1,024 GB
Why 1,024 and not 1,000? Computers count in binary, and 1,024 is 2 to the power 10, the power of two closest to a thousand.
The plan
Start with the number of bytes. While it is 1,024 or more, divide by 1,024 and move one unit up the list. When it drops below 1,024, you have found the right unit.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
71 Bytes in a form a person can read
fairTurn a byte count into something like 1.5 KB or 953.7 MB. Then explain why a 1,000,000,000-byte file is advertised as 1GB but shows as 953.7MB.
Stuck? Three hints, smallest first
- 1. Divide by 1024 repeatedly, counting how many times, and index into a list of unit names.
- 2. Stop when the value is under 1024 or you run out of units.
- 3. Disk makers count in powers of ten; operating systems count in powers of two. Both are "GB" in the marketing.
Step 1: a list of units
Put the unit names in an array, smallest first. The position in the array tells you how many times you have divided:
const BINARY = ['B', 'KB', 'MB', 'GB', 'TB'];
console.log(BINARY[0], BINARY[2]); // B MB
Divided zero times, the unit is BINARY[0], bytes. Divided twice, it is BINARY[2], megabytes.
Step 2: divide until it fits
const BINARY = ['B', 'KB', 'MB', 'GB', 'TB'];
function human(bytes) {
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < BINARY.length - 1) {
value /= 1024;
unit++;
}
return value + ' ' + BINARY[unit];
}
console.log(human(1024)); // 1 KB
console.log(human(1536)); // 1.5 KB
console.log(human(1e9)); // 953.67431640625 MB
value /= 1024 is short for value = value / 1024, and unit++ adds one to unit. The loop has two conditions. The first is the plan from above. The second, unit < BINARY.length - 1, stops it at the last unit in the list, so it can never step past 'TB' and read undefined from the array.
It works, but 953.67431640625 MB has far too many digits.
Step 3: round to one decimal place
toFixed(1) rounds to one decimal place and gives text. Wrapping it in Number(...) turns it back into a number, which drops a pointless .0:
console.log((953.67431640625).toFixed(1)); // 953.7
console.log((1).toFixed(1)); // 1.0
console.log(Number((1).toFixed(1))); // 1
So a whole gigabyte reads "1 GB" rather than "1.0 GB".
Step 4: the finished function
Small numbers can return straight away. The step size and the unit list become parameters with defaults, so the same function can count in thousands later:
const BINARY = ['B', 'KB', 'MB', 'GB', 'TB'];
function human(bytes, step = 1024, units = BINARY) {
if (bytes < step) return bytes + ' ' + units[0];
let value = bytes;
let unit = 0;
while (value >= step && unit < units.length - 1) {
value /= step;
unit++;
}
return Number(value.toFixed(1)) + ' ' + units[unit];
}
console.log(human(0)); // 0 B
console.log(human(1023)); // 1023 B
console.log(human(1024 ** 3)); // 1 GB
console.log(human(1024 ** 6)); // 1048576 TB
The last line is a huge number. The loop stops at TB, the end of the list, so you get a large TB figure instead of an error.
Step 5: the missing 46 MB
A memory card sold as "1 GB" holds 1,000,000,000 bytes. Drive makers count in steps of 1,000. Your computer counts in steps of 1,024. Same bytes, two answers:
const BINARY = ['B', 'KB', 'MB', 'GB', 'TB'];
function human(bytes, step = 1024, units = BINARY) {
if (bytes < step) return bytes + ' ' + units[0];
let value = bytes;
let unit = 0;
while (value >= step && unit < units.length - 1) {
value /= step;
unit++;
}
return Number(value.toFixed(1)) + ' ' + units[unit];
}
const DECIMAL = ['B', 'kB', 'MB', 'GB', 'TB'];
const humanDecimal = (bytes) => human(bytes, 1000, DECIMAL);
console.log(human(1e9)); // 953.7 MB
console.log(humanDecimal(1e9)); // 1 GB
Nothing is missing. "GB" just means two different sizes. There are separate names for the 1,024-based units (KiB, MiB, GiB), but few apps use them, so it helps to say which base you count in.
The full solution
The answer panel has human and humanDecimal, prints sizes from 0 bytes up to a billion bytes in both bases. Its checks cover the boundary at 1,023 and 1,024, whole megabytes and gigabytes, and the end of the unit list. Press Run to see the output.
const BINARY = ['B', 'KB', 'MB', 'GB', 'TB'];
function human(bytes, step = 1024, units = BINARY) {
if (bytes < step) return bytes + ' ' + units[0];
let value = bytes;
let unit = 0;
while (value >= step && unit < units.length - 1) {
value /= step;
unit++;
}
return Number(value.toFixed(1)) + ' ' + units[unit];
}
const DECIMAL = ['B', 'kB', 'MB', 'GB', 'TB'];
const humanDecimal = (bytes) => human(bytes, 1000, DECIMAL);
console.log('0 ->', human(0));
console.log('1023 ->', human(1023));
console.log('1024 ->', human(1024));
console.log('1536 ->', human(1536));
console.log('1e9 ->', human(1e9), 'but the box says', humanDecimal(1e9));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('small counts stay in bytes', human(0), '0 B');
test('and right up to the boundary', human(1023), '1023 B');
test('one kilobyte', human(1024), '1 KB');
test('one and a half', human(1536), '1.5 KB');
test('a megabyte', human(1024 * 1024), '1 MB');
test('a gigabyte', human(1024 ** 3), '1 GB');
test('a billion bytes is not a binary gigabyte', human(1e9), '953.7 MB');
test('though counted in thousands it is', humanDecimal(1e9), '1 GB');
test('and the scale runs out gracefully', human(1024 ** 6), '1048576 TB');
The 953.7 is not a rounding error, it is two different definitions of the same abbreviation. A gigabyte is 10⁹ bytes to a drive manufacturer and 2³⁰ to most operating systems, a 7.4% gap that grows with each step up the scale. The unambiguous names are KiB, MiB and GiB for the binary ones; almost nobody uses them, so state your base in the note if not on screen.
Two implementation details. The loop stops one short of the end of the unit list, so an absurd input degrades to "1048576 TB" instead of reading past the array and printing undefined. And Number(value.toFixed(1)) drops a pointless trailing .0, so a whole gigabyte reads "1 GB" rather than "1.0 GB".
Common mistakes
- Using
>instead of>=in the loop. Then exactly 1,024 bytes shows as "1024 B" instead of "1 KB". - No stop at the end of the unit list. A huge number would step past
'TB'and printundefined. - Mixing the two bases. Dividing by 1,000 but labeling the result with the 1,024-based meaning gives sizes that disagree with the file manager.
Try it yourself
- Add
'PB'(petabyte) to the end ofBINARYand check whathuman(1024 ** 6)prints now. - Change
humanso it rounds to two decimal places when the value is under 10, like1.46 GB. - Write
parseSize('1.5 KB')that turns the text back into a number of bytes.