Human-readable file size in JavaScript

“size” is in bytes, the rest you should be able to figure out.

function readableFileSize(size) {
    var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var i = 0;
    while(size >= 1024) {
        size /= 1024;
        ++i;
    }
    return size.toFixed(1) + ' ' + units[i];
}

4 thoughts on “Human-readable file size in JavaScript

  1. function fileSize(size) {
    var i = Math.floor( Math.log(size) / Math.log(1024) );
    return ( size / Math.pow(1024, i) ).toFixed(2) * 1 + ‘ ‘
    + [‘B’, ‘kB’, ‘MB’, ‘GB’, ‘TB’][i];
    }

  2. Thanks Sergei. That should work well too, although I don’t know why you have the *1 on there.

  3. *1 allows to show values such as 5.00 as 5, but keeps the decimals if there are any

  4. Thank you! This is a beautiful function!

Leave a Reply

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