JavaScript To Convert Bytes To MB, KB, Etc

I’m currently writing a converter for the HAR file format, which is used by Firebug, Chrome Developer Tools, JMeter, etc to record information about a page loading. The HAR format stores the size of downloaded components in bytes. I wanted to convert this into KB, MB, etc, for display.

I quickly found some nice code by ThomasR in the comments of a page on CodeAid, which looks like this:

[sourcecode language=”javascript”]function bytesToSize(bytes) {
var sizes = [‘Bytes’, ‘KB’, ‘MB’, ‘GB’, ‘TB’];
if (bytes == 0) return ‘n/a’;
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ‘ ‘ + sizes[i];
};[/sourcecode]

This will display 39212 bytes as 38KB. Nice, but I’d like slightly more precision. Fortunately further down in the comments, Jonathon includes the following code:

[sourcecode language=”javascript”]function bytesToSize(bytes) {
var sizes = [‘bytes’, ‘KiB’, ‘MiB’, ‘GiB’, ‘TiB’, ‘PiB’, ‘EiB’, ‘ZiB’, ‘YiB’];
if (bytes == 0) return ‘n/a’;
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
if (i == 0) { return (bytes / Math.pow(1024, i)) + ‘ ‘ + sizes[i]; }
return (bytes / Math.pow(1024, i)).toFixed(1) + ‘ ‘ + sizes[i];
}[/sourcecode]

This gives 1 decimal place, except for values that will remain as bytes, so that 39212 bytes will be displayed as 38.3KB. Perfect for me, although you can make it 2 decimal places by changing toFixed(1) to toFixed(2), etc.

I ended up going with a slightly optimised version of this (there was no need to do the Math on values that will remain as bytes):

[sourcecode language=”javascript”]function bytesToSize(bytes) {
var sizes = [‘Bytes’, ‘KB’, ‘MB’, ‘GB’, ‘TB’];
if (bytes == 0) return ‘n/a’;
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
if (i == 0) return bytes + ‘ ‘ + sizes[i];
return (bytes / Math.pow(1024, i)).toFixed(1) + ‘ ‘ + sizes[i];
};[/sourcecode]

but there are further optimisations in the comments, including a solution by Fergus which uses a ternary operator to reduce the code by a line. Great, but slight overkill to my mind. I do occasionally use ternary operators, but more often I opt to keep code readable by the most amount of people 🙂

One response on “JavaScript To Convert Bytes To MB, KB, Etc