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:

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];
};

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:

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];
}

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):

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];
};

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Anti-Spam Quiz: