我得到这段代码通过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));

其他回答

这个解决方案建立在以前的解决方案的基础上,但同时考虑了公制和二进制单位:

function formatBytes(bytes, decimals, binaryUnits) {
    if(bytes == 0) {
        return '0 Bytes';
    }
    var unitMultiple = (binaryUnits) ? 1024 : 1000; 
    var unitNames = (unitMultiple === 1024) ? // 1000 bytes in 1 Kilobyte (KB) or 1024 bytes for the binary version (KiB)
        ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']: 
        ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var unitChanges = Math.floor(Math.log(bytes) / Math.log(unitMultiple));
    return parseFloat((bytes / Math.pow(unitMultiple, unitChanges)).toFixed(decimals || 0)) + ' ' + unitNames[unitChanges];
}

例子:

formatBytes(293489203947847, 1);    // 293.5 TB
formatBytes(1234, 0);   // 1 KB
formatBytes(4534634523453678343456, 2); // 4.53 ZB
formatBytes(4534634523453678343456, 2, true));  // 3.84 ZiB
formatBytes(4566744, 1);    // 4.6 MB
formatBytes(534, 0);    // 534 Bytes
formatBytes(273403407, 0);  // 273 MB

只是稍微修改了@zayarTun答案的代码,以包括一个额外的参数,表示结果中的小数数(如果小数为零,则不需要显示像15.00 KB这样的结果,而是15 KB就足够了,这就是为什么我在parseFloat()中包装结果值)

  bytesForHuman(bytes, decimals = 2) {
    let units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']

    let i = 0
    
    for (i; bytes > 1024; i++) {
        bytes /= 1024;
    }

    return parseFloat(bytes.toFixed(decimals)) + ' ' + units[i]
  }

由此可见:(来源)


Unminified and es6’ed:(社区)

function formatBytes(bytes, decimals = 2) { if (!+bytes) return '0 Bytes' const k = 1024 const dm = decimals < 0 ? 0 : decimals const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] const i = Math.floor(Math.log(bytes) / Math.log(k)) return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}` } // Demo code document.body.innerHTML += `<input type="text" oninput="document.querySelector('p').innerHTML=formatBytes(this.value)" value="1000"><p>1000 Bytes</p>`

简化版(由StackOverflow社区提供,由JSCompress提供)

function formatBytes(a,b=2){if(!+a)return"0 Bytes";const c=0>b?0:b,d=Math.floor(Math.log(a)/Math.log(1024));return`${parseFloat((a/Math.pow(1024,d)).toFixed(c))} ${["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][d]}`}

用法:

// formatBytes(bytes, decimals)

formatBytes(1024)       // 1 KB
formatBytes('1024')     // 1 KB
formatBytes(1234)       // 1.21 KB
formatBytes(1234, 3)    // 1.205 KB
formatBytes(0)          // 0 Bytes
formatBytes('0')        // 0 Bytes

PS:更改k = 1000或大小=["…如你所愿(比特或字节)

我让算法快了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

耶稣基督!

使用位操作将是一个更好的解决方案。试试这个

function formatSizeUnits(bytes)
{
    if ( ( bytes >> 30 ) & 0x3FF )
        bytes = ( bytes >>> 30 ) + '.' + ( bytes & (3*0x3FF )) + 'GB' ;
    else if ( ( bytes >> 20 ) & 0x3FF )
        bytes = ( bytes >>> 20 ) + '.' + ( bytes & (2*0x3FF ) ) + 'MB' ;
    else if ( ( bytes >> 10 ) & 0x3FF )
        bytes = ( bytes >>> 10 ) + '.' + ( bytes & (0x3FF ) ) + 'KB' ;
    else if ( ( bytes >> 1 ) & 0x3FF )
        bytes = ( bytes >>> 1 ) + 'Bytes' ;
    else
        bytes = bytes + 'Byte' ;
    return bytes ;
}