我得到这段代码通过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));
这里有一句话:
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,但我对额外的精度很满意。
我只是想分享我的想法。我遇到了这个问题,所以我的解决方案是这样的。这将把低单位转换为高单位,反之亦然,只需提供参数toUnit和fromUnit
export function fileSizeConverter(size: number, fromUnit: string, toUnit: string ): number | string {
const units: string[] = ['B', 'KB', 'MB', 'GB', 'TB'];
const from = units.indexOf(fromUnit.toUpperCase());
const to = units.indexOf(toUnit.toUpperCase());
const BASE_SIZE = 1024;
let result: number | string = 0;
if (from < 0 || to < 0 ) { return result = 'Error: Incorrect units'; }
result = from < to ? size / (BASE_SIZE ** to) : size * (BASE_SIZE ** from);
return result.toFixed(2);
}
我从这里得到了灵感