2

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?

KingKongFrog
  • 13,946
  • 21
  • 75
  • 124
Tiny
  • 27,221
  • 105
  • 339
  • 599
  • possible duplicate of [Equivalent of String.format in JQuery](http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery) – Mike Samuel Apr 15 '13 at 20:06
  • @Mike Samuel : I have seen that question before asking this one but that question is mostly related to ASP.NET. – Tiny Apr 15 '13 at 20:12
  • converting `sprintf` style format strings to the String.format convention should be trivial since the only format you use is `.1f` which can be handled via `myNumber.toFixed(1)`. – Mike Samuel Apr 15 '13 at 20:21

1 Answers1

9

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
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124