我得到这段代码通过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;
}
这是正确的做法吗?有没有更简单的方法?
const byteConversion = (bytes: number, decimals = 2) => {
if (bytes === 0) return '0 B';
const kiloByte = 1000;
const decimal = decimals < 0 ? 0 : decimals;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i: number = Math.floor(Math.log(bytes) / Math.log(kiloByte));
return `${parseFloat((bytes / kiloByte ** i).toFixed(decimal))} ${sizes[i]}`;
};
这里有一句话:
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;
}
我最初在一个文件上传项目中使用@ al冰岛jm的答案,但最近遇到了一个问题,一个文件是0.98kb,但读取为1.02mb。下面是我现在使用的更新代码。
function formatBytes(bytes){
var kb = 1024;
var ndx = Math.floor( Math.log(bytes) / Math.log(kb) );
var fileSizeTypes = ["bytes", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb"];
return {
size: +(bytes / kb / kb).toFixed(2),
type: fileSizeTypes[ndx]
};
}
在像这样添加文件之后,上面的函数将被调用
// In this case `file.size` equals `26060275`
formatBytes(file.size);
// returns `{ size: 24.85, type: "mb" }`
当然,Windows读取的文件为24.8mb,但我对额外的精度很满意。
当与字节相关时,有两种真实的方法来表示大小,它们是SI单位(10^3)或IEC单位(2^10)。也有JEDEC,但他们的方法是模糊的和令人困惑的。我注意到其他示例有错误,例如使用KB而不是KB来表示千字节,因此我决定编写一个函数,使用当前接受的度量单位的范围来解决这些情况。
在结尾有一个格式化的地方,这将使数字看起来更好一点(至少在我看来),如果它不适合你的目的,请随意删除这个格式。
享受。
// pBytes: the size in bytes to be converted.
// pUnits: 'si'|'iec' si units means the order of magnitude is 10^3, iec uses 2^10
function prettyNumber(pBytes, pUnits) {
// Handle some special cases
if(pBytes == 0) return '0 Bytes';
if(pBytes == 1) return '1 Byte';
if(pBytes == -1) return '-1 Byte';
var bytes = Math.abs(pBytes)
if(pUnits && pUnits.toLowerCase() && pUnits.toLowerCase() == 'si') {
// SI units use the Metric representation based on 10^3 as a order of magnitude
var orderOfMagnitude = Math.pow(10, 3);
var abbreviations = ['Bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
} else {
// IEC units use 2^10 as an order of magnitude
var orderOfMagnitude = Math.pow(2, 10);
var abbreviations = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
}
var i = Math.floor(Math.log(bytes) / Math.log(orderOfMagnitude));
var result = (bytes / Math.pow(orderOfMagnitude, i));
// This will get the sign right
if(pBytes < 0) {
result *= -1;
}
// This bit here is purely for show. it drops the percision on numbers greater than 100 before the units.
// it also always shows the full number of bytes if bytes is the unit.
if(result >= 99.995 || i==0) {
return result.toFixed(0) + ' ' + abbreviations[i];
} else {
return result.toFixed(2) + ' ' + abbreviations[i];
}
}
这是一个字节应该如何显示给人类:
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));