我正在尝试如下转换HTML中以字节表示的文件大小(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];
}

但是我需要在需要时以SI和二进制单位表示文件大小,
kB<--->KiB
MB<--->MiB
GB<--->GiB
TB<--->TiB
EB<--->EiB

可以使用以下代码在Java中完成此操作(对方法使用一个附加的 bool(boolean) 参数)。
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);
}

JavaScript中的等效代码如下。
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);
}

我无法按照前面的代码片段(最后一个)中的注释行在JavaScript中编写等效语句。当然,还有其他方法可以在JavaScript中执行此操作,但是我正在寻找一种简洁的方法,更准确地说是,如果可以在JavaScript / jQuery中编写等效的语句。可能吗?

最佳答案

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

09-30 17:34
查看更多