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

这是正确的做法吗?有没有更简单的方法?


当前回答

这是目前排名最高的答案的后续。

边界情况

我发现了一个边缘情况:非常少量的字节!具体来说,当字节数在-1和1之间(独占)时。

例如,考虑0.25字节。在这种情况下,Math.floor(Math.log(0.25) / Math.log(1024))将返回-1。由于-1不是一个有效的索引,formatBytes(0.25)将返回类似“0.25 undefined”的值。

下面是一个使用Wolfram Alpha的边缘情况的示例。

Fix

我通过添加Math来解决这个问题。马克斯(0,…):

数学。max(0, Math.floor(Math.log(bytes) / Math.log(1024))

数学。Max(0,…)确保索引值始终至少为0。

其他回答

function bytesToSize(bytes) { var sizes = ['B', 'K', 'M', 'G', 'T', 'P']; for (var i = 0; i < sizes.length; i++) { if (bytes <= 1024) { return bytes + ' ' + sizes[i]; } else { bytes = parseFloat(bytes / 1024).toFixed(2) } } return bytes + ' P'; } console.log(bytesToSize(234)); console.log(bytesToSize(2043)); console.log(bytesToSize(20433242)); console.log(bytesToSize(2043324243)); console.log(bytesToSize(2043324268233)); console.log(bytesToSize(2043324268233343));

这不是关于将字节转换为其他单位,但它有助于正确显示当前地区的数字和单位:

bytes.toLocaleString(undefined, {
  style: 'unit',
  unit: 'gigabyte',
})

更多选择和细节可以在这里找到:https://v8.dev/features/intl-numberformat#units

函数by睾丸(字节){ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; If (bytes === 0)返回'n/a'; const i = Math.min(Math.floor(Math.log(bytes) / Math.log(1024))),大小。长度- 1); 如果(i === 0)返回' ${bytes} ${sizes[i]} '; 返回“${(字节/(1024 * *我)).toFixed(1)} ${大小[我]}'; } console.log (bytesToSize (400000)) console.log (bytesToSize (5000000))

@ al冰岛jm也给出了同样的答案,但以一种“更说教”的方式。谢谢!= D

function formatBytes(numBytes, decPlaces) {
    /* Adjust the number of bytes informed for the most appropriate metric according
    to its value.

    Args:
        numBytes (number): The number of bytes (integer);
        decPlaces (Optional[number])): The number of decimal places (integer). If
            it is "undefined" the value "2" will be adopted.

    Returns:
        string: The number adjusted together with the most appropriate metric. */

    if (numBytes === 0) {
        return "0 Bytes";
    }

    // NOTE: 1 KB is equal to 1024 Bytes. By Questor
    // [Ref(s).: https://en.wikipedia.org/wiki/Kilobyte ]
    var oneKByte = 1024;

    // NOTE: Treats if the "decPlaces" is "undefined". If it is "undefined" the value
    // "2" will be adopted. By Questor
    if (decPlaces === undefined || decPlaces === "") {
        decPlaces = 2;
    }

    var byteMtrcs = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
    // Byte Metrics

    // NOTE: Defines the factor for the number of bytes and the metric. By Questor
    var mtrcNumbFactor = Math.floor(Math.log(numBytes) / Math.log(oneKByte));
    // Metrics Number Factor

    return parseFloat((numBytes / Math.pow(oneKByte, mtrcNumbFactor)).
            toFixed(decPlaces)) + " " + byteMtrcs[mtrcNumbFactor];
}

这里有一句话:

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;
}