我得到这段代码通过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;
}
这是正确的做法吗?有没有更简单的方法?
我让算法快了7倍(就像忍者一样):
function rafaelFormatBytes(number){
if(number == null || number === undefined || number <= 0) {
return '0 Bytes';
}
var scaleCounter = 0;
var scaleInitials = [' Bytes',' KB',' MB',' GB',' TB',' PB',' EB',' ZB',' YB'];
while (number >= 1024 && scaleCounter < scaleInitials.length - 1){
number /= 1024;
scaleCounter++;
}
if(scaleCounter >= scaleInitials.length) scaleCounter = scaleInitials.length - 1;
var compactNumber = number.toFixed(2)
.replace(/\.?0+$/,'')
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
compactNumber += scaleInitials[scaleCounter];
return compactNumber.trim();
}
var testNum = 0;
var startTime, endTime;
function start() {
startTime = new Date();
};
function end() {
endTime = new Date();
var timeDiff = endTime - startTime; //in ms
// strip the ms
timeDiff /= 1000;
// get seconds
var seconds = Math.round(timeDiff, 5);
console.log(timeDiff + " seconds");
}
function formatBytes(a,b=2,k=1024){with(Math){let d=floor(log(a)/log(k));return 0==a?"0 Bytes":parseFloat((a/pow(k,d)).toFixed(max(0,b)))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][d]}}
console.log(formatBytes(1000000000000000000000000000));
console.log(rafaelFormatBytes(1000000000000000000000000000));
start();
for(i=0; i<100000; i++){
formatBytes(1000000000000000);
}
end();
start();
for(i=0; i<100000; i++){
rafaelFormatBytes(1000000000000000);
}
end();
... 输出:
827.18 YB
827.18 YB
0.293 seconds
0.039 seconds
耶稣基督!
这是一个坚实的有效的方法来转换字节。你唯一需要做的就是安装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);
}
}
我最初在一个文件上传项目中使用@ 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,但我对额外的精度很满意。
更灵活和考虑最大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]
}`;
}
我有一个问题的元数据从服务器返回不同大小的单位。我使用了@Alicejim response,并试图让它更通用。在这里分享代码,也许会帮助到一些人。
enum SizeUnits {
Bytes = 'Bytes',
KB = 'KB',
MB = 'MB',
GB = 'GB',
TB = 'TB',
PB = 'PB',
EB = 'EB',
ZB = 'ZB',
YB = 'YB'
}
function convertSizeUnites(size: number, sourceSizeUnits: SizeUnits, targetSizeUnits: SizeUnits) {
const i = Object.keys(SizeUnits).indexOf(sourceSizeUnits);
const sizeInBytes = size * Math.pow(1024, i);
const j = Object.keys(SizeUnits).indexOf(targetSizeUnits);
return sizeInBytes / Math.pow(1024, j);
}
function formatSize(size: number, measureUnit: SizeUnits, decimals = 2) {
if (size === 0) return '0 Bytes';
const sizeInBytes = convertSizeUnites(size, measureUnit, SizeUnits.Bytes);
const dm = decimals < 0 ? 0 : decimals;
const i = Math.floor(Math.log(sizeInBytes) / Math.log(1024));
return parseFloat((sizeInBytes / Math.pow(1024, i)).toFixed(dm)) + ' ' +
Object.keys(SizeUnits)[i];
}