javascript - 如何在 javascript 中将字节格式化为人类可读的文本?

标签 javascript

我正在尝试按如下方式转换以字节表示的文件大小(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 参数)。

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

关于javascript - 如何在 javascript 中将字节格式化为人类可读的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16023824/

相关文章:

JavaScript 代码优化

java - JS 中的 .Jar 文件

javascript - "selectRootElement"和 "createViewRoot"有什么区别

javascript - 使用对象原型(prototype)作为默认值有多好?

javascript - 如何格式化包含变量的正则表达式?

javascript - 当我不访问某个网站时,是否会为该网站指定 Chrome 扩展程序?

Javascript apply——继承类

javascript - 如何读取netsuite中的子列表数据?

javascript - 为什么有些脚本会混淆元素名称? (例如 "d\u0069\x76"为 "div")

javascript - 使用jQuery点击按钮下载图片