我得到这段代码通过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;
}
这是正确的做法吗?有没有更简单的方法?
这是一个字节应该如何显示给人类:
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));
更灵活和考虑最大pow尺寸列表
(升级后的l2aelba答案)
function formatBytes(bytes, decimals = 2, isBinary = false) {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; // or ['B', 'KB', 'MB', 'GB', 'TB']
if (!+bytes) {
return `0 ${sizes[0]}`;
}
const inByte = isBinary ? 1024 : 1000;
const dm = decimals < 0 ? 0 : decimals;
const pow = Math.floor(Math.log(bytes) / Math.log(inByte));
const maxPow = Math.min(pow, sizes.length - 1);
return `${parseFloat((bytes / Math.pow(inByte, maxPow)).toFixed(dm))} ${
sizes[maxPow]
}`;
}
这是一个坚实的有效的方法来转换字节。你唯一需要做的就是安装mathjs库进行精确的计算。复制粘贴即可。
import { multiply, divide, round } from "mathjs";
class Size {
constructor(value, unit) {
this.value = value;
this.unit = unit.toUpperCase();
}
}
async function byteToSize(bytes) {
const B = 1;
const KB = multiply(B, 1024);
const MB = multiply(KB, 1024);
const GB = multiply(MB, 1024);
const TB = multiply(GB, 1024);
const PB = multiply(TB, 1024);
if (bytes <= KB) {
// @returns BYTE
const result = round(divide(bytes, B));
const unit = `B`;
return new Size(result, unit);
}
if (bytes <= MB) {
// @returns KILOBYTE
const result = round(divide(bytes, KB));
const unit = `KB`;
return new Size(result, unit);
}
if (bytes <= GB) {
// @returns MEGABYTE
const result = round(divide(bytes, MB));
const unit = `MB`;
return new Size(result, unit);
}
if (bytes <= TB) {
// @returns GIGABYTE
const result = round(divide(bytes, GB));
const unit = `GB`;
return new Size(result, unit);
}
if (bytes <= PB) {
// @returns TERABYTE
const result = divide(bytes, TB).toFixed(2);
const unit = `TB`;
return new Size(result, unit);
}
if (bytes >= PB) {
// @returns PETABYTE
const result = divide(bytes, PB).toFixed(2);
const unit = `PB`;
return new Size(result, unit);
}
}