Tiny
Tiny

Reputation: 27899

How do I format bytes to human readable text in javascript?

I'm trying to convert a file size represented in bytes in JavaScript as follows (HTML 5).

function formatBytes(bytes)
{
    var sizes = ['Bytes', 'kB', 'MB', 'GB', 'TB'];
    if (bytes == 0) 
    {
        return 'n/a';
    }
    var i = parseInt(Math.log(bytes) / Math.log(1024));
    return Math.round(bytes / Math.pow(1024, i), 2) + sizes[i];
}

But I need to represent the file size in both SI and binary units as and when required like,

kB<--->KiB
MB<--->MiB
GB<--->GiB
TB<--->TiB
EB<--->EiB

This could be done in Java like the following (using one additional boolean parameter to the method).

public static String formatBytes(long size, boolean si)
{
    final int unitValue = si ? 1000 : 1024;
    if (size < unitValue) 
    {
        return size + " B";
    }
    int exp = (int) (Math.log(size) / Math.log(unitValue));
    String initLetter = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
    return String.format("%.1f %sB", size / Math.pow(unitValue, exp), initLetter);
}

Somewhat equivalent code in JavaScript could be as follows.

function formatBytes(size, si)
{
    var unitValue = si ? 1000 : 1024;
    if (size < unitValue) 
    {
        return size + " B";
    }
    var exp = parseInt((Math.log(size) / Math.log(unitValue)));
    var initLetter = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
    alert(size / Math.pow(unitValue, exp)+initLetter);
    //return String.format("%.1f %sB", size / Math.pow(unitValue, exp), initLetter);
}

I couldn't write the equivalent statement in JavaScript as the commented line in the preceding snippet (the last one) indicates. Of course, there are other ways to do this in JavaScript but I'm looking for a concise way and more precisely, if it is possible to write the equivalent statement in JavaScript/jQuery. Is it possible?

Upvotes: 2

Views: 2331

Answers (1)

KingKongFrog
KingKongFrog

Reputation: 14419

http://jsbin.com/otecul/1/edit

function humanFileSize(bytes, si) {
    var thresh = si ? 1000 : 1024;
    if(bytes < thresh) return bytes + ' B';
    var units = si ? ['kB','MB','GB','TB','PB','EB','ZB','YB'] : ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'];
    var u = -1;
    do {
        bytes /= thresh;
        ++u;
    } while(bytes >= thresh);
    return bytes.toFixed(1)+' '+units[u];
};

humanFileSize(6583748758); //6.1 GiB
humanFileSize(6583748758,1) //6.4 GB

Upvotes: 9

Related Questions