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

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


当前回答

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

其他回答

您可以使用filesizejs库。

一行程序

const b2s = t = > {let’e = Math .对数(t) / 10 | 0; return (t / 1024 * * (e = e < = 0 ? 0 toFixed: e))(3) +“BKMGP”[e]}; console . log (b2s (0)); console . log (b2s (123)); console . log (b2s (123123)); console . log (b2s (123123123)); console . log (b2s (123123123123)); console . log (b2s (123123123123123));

我只是想分享我的想法。我遇到了这个问题,所以我的解决方案是这样的。这将把低单位转换为高单位,反之亦然,只需提供参数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);
}

我从这里得到了灵感

const byteConversion = (bytes: number, decimals = 2) => {
if (bytes === 0) return '0 B';

const kiloByte = 1000;
const decimal = decimals < 0 ? 0 : decimals;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

const i: number = Math.floor(Math.log(bytes) / Math.log(kiloByte));

return `${parseFloat((bytes / kiloByte ** i).toFixed(decimal))} ${sizes[i]}`;

};

我有一个问题的元数据从服务器返回不同大小的单位。我使用了@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];
}