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