我得到这段代码通过PHP隐蔽大小字节。
现在我想使用JavaScript将这些大小转换为人类可读的大小。我尝试将这段代码转换为JavaScript,看起来像这样:
function formatSizeUnits(bytes){
if (bytes >= 1073741824) { bytes = (bytes / 1073741824).toFixed(2) + " GB"; }
else if (bytes >= 1048576) { bytes = (bytes / 1048576).toFixed(2) + " MB"; }
else if (bytes >= 1024) { bytes = (bytes / 1024).toFixed(2) + " KB"; }
else if (bytes > 1) { bytes = bytes + " bytes"; }
else if (bytes == 1) { bytes = bytes + " byte"; }
else { bytes = "0 bytes"; }
return bytes;
}
这是正确的做法吗?有没有更简单的方法?
这里有一句话:
val => ['Bytes','Kb','Mb','Gb','Tb'][Math.floor(Math.log2(val)/10)]
甚至:
v => 'BKMGT'[~~(Math.log2(v)/10)]
与数:
function shortenBytes(n) {
const k = n > 0 ? Math.floor((Math.log2(n)/10)) : 0;
const rank = (k > 0 ? 'KMGT'[k - 1] : '') + 'b';
const count = Math.floor(n / Math.pow(1024, k));
return count + rank;
}
这是一个字节应该如何显示给人类:
function bytesToHuman(bytes, decimals = 2) {
// https://en.wikipedia.org/wiki/Orders_of_magnitude_(data)
const units = ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"]; // etc
let i = 0;
let h = 0;
let c = 1 / 1023; // change it to 1024 and see the diff
for (; h < c && i < units.length; i++) {
if ((h = Math.pow(1024, i) / bytes) >= c) {
break;
}
}
// remove toFixed and let `locale` controls formatting
return (1 / h).toFixed(decimals).toLocaleString() + " " + units[i];
}
// test
for (let i = 0; i < 9; i++) {
let val = i * Math.pow(10, i);
console.log(val.toLocaleString() + " bytes is the same as " + bytesToHuman(val));
}
// let's fool around
console.log(bytesToHuman(1023));
console.log(bytesToHuman(1024));
console.log(bytesToHuman(1025));