【问题标题】:Converting file size in bytes to human-readable string将文件大小(以字节为单位)转换为人类可读的字符串
【发布时间】:2012-05-12 07:36:43
【问题描述】:

我正在使用此函数将文件大小(以字节为单位)转换为人类可读的文件大小:

function getReadableFileSizeString(fileSizeInBytes) {
    var i = -1;
    var byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
    do {
        fileSizeInBytes = fileSizeInBytes / 1024;
        i++;
    } while (fileSizeInBytes > 1024);

    return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
};

但是,这似乎不是 100% 准确的。例如:

getReadableFileSizeString(1551859712); // output is "1.4 GB"

这不应该是"1.5 GB"吗?似乎除以 1024 正在失去精度。我完全误解了某事还是有更好的方法来做到这一点?

【问题讨论】:

  • getReadableFileSizeString(0);返回 0.1kb ;p
  • 为什么要1.5? 1.445281982421875 正确舍入为 1.4。
  • 1551859712/(1024^3)=1.445281982421875 这是正确的!
  • 我喜欢你添加了YB。值得怀疑的是,任何人都会为他的 DB 获得 1 YB。它将花费100 trillion dollars
  • @guyarad - 有一张 50 年前的 5MB 硬盘驱动器的著名图片(房间大小,重约一吨)。我敢肯定,那时他们甚至没有梦想过 GB 和 TB,看看我们今天所处的位置......永远不要说永远;-)

标签: javascript filesize human-readable


【解决方案1】:

这是我写的:

/**
 * Format bytes as human-readable text.
 * 
 * @param bytes Number of bytes.
 * @param si True to use metric (SI) units, aka powers of 1000. False to use 
 *           binary (IEC), aka powers of 1024.
 * @param dp Number of decimal places to display.
 * 
 * @return Formatted string.
 */
function humanFileSize(bytes, si=false, dp=1) {
  const thresh = si ? 1000 : 1024;

  if (Math.abs(bytes) < thresh) {
    return bytes + ' B';
  }

  const units = si 
    ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] 
    : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
  let u = -1;
  const r = 10**dp;

  do {
    bytes /= thresh;
    ++u;
  } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);


  return bytes.toFixed(dp) + ' ' + units[u];
}


console.log(humanFileSize(1551859712))  // 1.4 GiB
console.log(humanFileSize(5000, true))  // 5.0 kB
console.log(humanFileSize(5000, false))  // 4.9 KiB
console.log(humanFileSize(-10000000000000000000000000000))  // -8271.8 YiB
console.log(humanFileSize(999949, true))  // 999.9 kB
console.log(humanFileSize(999950, true))  // 1.0 MB
console.log(humanFileSize(999950, true, 2))  // 999.95 kB
console.log(humanFileSize(999500, true, 0))  // 1 MB

【讨论】:

  • 我正在做一个调整:在评估阈值时,取绝对值。这样该函数将支持负值。不错的功能!感谢您不使用 switch 语句!
  • @AaronBlenkush:你什么时候会有一个负的文件大小?
  • 我刚刚将您的函数复制到了我用来在“清理”操作后显示大小增量的 Google 表格中。之前、之后和差异。清理操作导致一些数据库表的增长,而其他的减少。例如,表 A 的差异为 -1.95 MB,而表 B 的差异为 500 kB。因此:正面和负面:-)
  • 这里是脚本的压缩版本:function humanFileSize(B,i){var e=i?1e3:1024;if(Math.abs(B)&lt;e)return B+" B";var a=i?["kB","MB","GB","TB","PB","EB","ZB","YB"]:["KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"],t=-1;do B/=e,++t;while(Math.abs(B)&gt;=e&amp;&amp;t&lt;a.length-1);return B.toFixed(1)+" "+a[t]}
  • @RANders00:感谢缩小版。不过,你能告诉我,为什么你在 E oft EiB?这是否旨在成为水印,以便您可以跟踪谁使用了此代码?如果是这样,我认为你应该在你的帖子中做到这一点。
【解决方案2】:

计算的另一个体现

function humanFileSize(size) {
    var i = Math.floor( Math.log(size) / Math.log(1024) );
    return ( size / Math.pow(1024, i) ).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];
};

【讨论】:

  • 似乎无法处理 0
  • 它处理还是不处理0?毕竟,这与 if(size == 0) {} else {} 仍然比我见过的大多数更优雅。
  • 将第一行更改为 var i = size == 0 ? 0 : Math.floor( Math.log(size) / Math.log(1024) ); 似乎可以解决问题,如果它是 0。它将返回“0 B”。
  • 仅供参考;我知道答案是纯 JavaScript,但如果有人不想在 TypeScript 中使用它,它就不起作用(没有正确输入,因为你正在做 toFixed 然后用字符串做数学运算。@ 987654324@做什么?
  • *1 将数据类型从字符串更改为数字,因此对于值1024,您将得到1 kB 而不是1.00 kB。你可以通过 Number((size / Math.pow(1024, i)).toFixed(2)) 来完成同样的事情,让 TypeScript 开心。
【解决方案3】:

这取决于您要使用二进制还是十进制约定。

例如,RAM 始终以二进制测量,因此将 1551859712 表示为 ~1.4GiB 是正确的。

另一方面,硬盘制造商喜欢使用十进制,所以他们称它为~1.6GB。

为了混淆,软盘混合使用了两种系统——它们的 1MB 实际上是 1024000 字节。

【讨论】:

  • 超级有趣 ;-) “只是为了混淆,软盘混合使用了两种系统——它们的 1MB 实际上是 1024000 字节。”
  • true,RAM 大小使用 IEC 单位测量,磁盘大小使用公制.. 有一个同构 npm 模块可以转换两者:byte-size
【解决方案4】:

这是一个将数字转换为符合新国际标准的可读字符串的原型。

有两种方法可以表示大数字:您可以显示 它们是 1000 = 10 3(以 10 为底)或 1024 = 2 10(以 2 为底)的倍数。如果 你除以 1000,你可能使用 SI 前缀名称,如果你 除以 1024,您可能使用 IEC 前缀名称。问题 从除以 1024 开始。许多应用程序使用 SI 前缀 它的名称和一些使用 IEC 前缀名称。目前的情况 是一个烂摊子。如果您看到 SI 前缀名称,您不知道是否 数字除以 1000 或 1024

https://wiki.ubuntu.com/UnitsPolicy

http://en.wikipedia.org/wiki/Template:Quantities_of_bytes

Object.defineProperty(Number.prototype,'fileSize',{value:function(a,b,c,d){
 return (a=a?[1e3,'k','B']:[1024,'K','iB'],b=Math,c=b.log,
 d=c(this)/c(a[0])|0,this/b.pow(a[0],d)).toFixed(2)
 +' '+(d?(a[1]+'MGTPEZY')[--d]+a[2]:'Bytes');
},writable:false,enumerable:false});

此函数不包含loop,因此它可能比其他一些函数更快。

用法:

IEC 前缀

console.log((186457865).fileSize()); // default IEC (power 1024)
//177.82 MiB
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB

SI 前缀

console.log((186457865).fileSize(1)); //1,true for SI (power 1000)
//186.46 MB 
//kB,MB,GB,TB,PB,EB,ZB,YB

我将 IEC 设置为默认值,因为我总是使用二进制模式来计算文件的大小...使用 1024 的幂


如果您只希望其中一个包含在一个简短的 oneliner 函数中:

SI

function fileSizeSI(a,b,c,d,e){
 return (b=Math,c=b.log,d=1e3,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
 +' '+(e?'kMGTPEZY'[--e]+'B':'Bytes')
}
//kB,MB,GB,TB,PB,EB,ZB,YB

IEC

function fileSizeIEC(a,b,c,d,e){
 return (b=Math,c=b.log,d=1024,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
 +' '+(e?'KMGTPEZY'[--e]+'iB':'Bytes')
}
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB

用法:

console.log(fileSizeIEC(7412834521));

如果您对功能有任何疑问,请询问

【讨论】:

  • 非常简洁的代码,不过我个人会添加几个额外的字符来控制小数位。
  • 嗨!实际上,代码是我第一次在 jsfiddle 中编写它的方式。在过去的几年里,我学会了自己使用速记和按位。移动设备速度慢,互联网速度慢,空间不大......这样做我节省了很多时间。但这还不是全部,每个浏览器的整体性能都大幅提高,整个代码加载速度更快……我不使用 jquery,所以我不必每次都加载 100kb。我还需要说,我也在微控制器、智能电视、游戏机中编写 javascript。那些空间有限(MCU)、性能(SmartTV),自然有时连接速度很慢(移动)
  • 表示希望你理解我的选择。我所能做的就是解释你不明白的东西,或者另一方面我总是很乐意学习新事物。如果我的代码中有什么东西可以提高性能或节省空间,我很高兴听到它。
  • 缩小应该是您构建过程的一部分,而不是您的编码风格。没有认真的开发人员会使用此代码,因为阅读和验证正确性需要很长时间。
  • 对于那些讨厌看到“15.00 Bytes”的人,你可以稍微修改一下这部分:.toFixed(e ? 2 : 0)
【解决方案5】:
sizeOf = function (bytes) {
  if (bytes == 0) { return "0.00 B"; }
  var e = Math.floor(Math.log(bytes) / Math.log(1024));
  return (bytes/Math.pow(1024, e)).toFixed(2)+' '+' KMGTP'.charAt(e)+'B';
}

sizeOf(2054110009);
//=> "1.91 GB"

sizeOf(7054110);
//=> "6.73 MB"

sizeOf((3*1024*1024));
//=> "3.00 MB"

【讨论】:

  • 如果你想去掉多余的字节空间,你可以使用零宽度空间\u200b:'\u200bKMGTP'
【解决方案6】:

作为 ReactJS 组件的解决方案

Bytes = React.createClass({
    formatBytes() {
        var i = Math.floor(Math.log(this.props.bytes) / Math.log(1024));
        return !this.props.bytes && '0 Bytes' || (this.props.bytes / Math.pow(1024, i)).toFixed(2) + " " + ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][i]
    },
    render () {
        return (
            <span>{ this.formatBytes() }</span>
        );
    }
});

更新 对于那些使用 es6 的人来说,这里是同一个组件的无状态版本

const sufixes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const getBytes = (bytes) => {
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return !bytes && '0 Bytes' || (bytes / Math.pow(1024, i)).toFixed(2) + " " + sufixes[i];
};

const Bytes = ({ bytes }) => (<span>{ getBytes(bytes) }</span>);

Bytes.propTypes = {
  bytes: React.PropTypes.number,
};

【讨论】:

  • 太好了,谢谢。您只是在 getBytes 函数的第一行中的 Math.log() 中忘记了“字节”
  • 非常好。为了消除歧义,使用 ES6 表示法,您可以使用:return (!bytes && '0 Bytes') || ${(bytes / (1024 ** i)).toFixed(2)} ${suffixes[i]};
【解决方案7】:

基于cocco 的想法,这里有一个不太紧凑但希望更全面的示例。

<!DOCTYPE html>
<html>
<head>
<title>File info</title>

<script>
<!--
function fileSize(bytes) {
    var exp = Math.log(bytes) / Math.log(1024) | 0;
    var result = (bytes / Math.pow(1024, exp)).toFixed(2);

    return result + ' ' + (exp == 0 ? 'bytes': 'KMGTPEZY'[exp - 1] + 'B');
}

function info(input) {
    input.nextElementSibling.textContent = fileSize(input.files[0].size);
} 
-->
</script>
</head>

<body>
<label for="upload-file"> File: </label>
<input id="upload-file" type="file" onchange="info(this)">
<div></div>
</body>
</html> 

【讨论】:

    【解决方案8】:

    另一个类似的例子

    function fileSize(b) {
        var u = 0, s=1024;
        while (b >= s || -b >= s) {
            b /= s;
            u++;
        }
        return (u ? b.toFixed(1) + ' ' : b) + ' KMGTPEZY'[u] + 'B';
    }
    

    它衡量的性能比其他具有相似功能的产品好到可以忽略不计。

    【讨论】:

    • 这确实提供了比其他一些答案更好的性能。我正在使用这个。在我进行定期计算时,其他一些人让我的 Chrome 选项卡挂起并占用了 99.9% 的 CPU。
    【解决方案9】:

    我想要“文件管理器”行为(例如,Windows 资源管理器),其中小数位数与数字大小成正比。似乎没有其他答案可以做到这一点。

    function humanFileSize(size) {
        if (size < 1024) return size + ' B'
        let i = Math.floor(Math.log(size) / Math.log(1024))
        let num = (size / Math.pow(1024, i))
        let round = Math.round(num)
        num = round < 10 ? num.toFixed(2) : round < 100 ? num.toFixed(1) : round
        return `${num} ${'KMGTPEZY'[i-1]}B`
    }
    

    这里有一些例子:

    humanFileSize(0)          // "0 B"
    humanFileSize(1023)       // "1023 B"
    humanFileSize(1024)       // "1.00 KB"
    humanFileSize(10240)      // "10.0 KB"
    humanFileSize(102400)     // "100 KB"
    humanFileSize(1024000)    // "1000 KB"
    humanFileSize(12345678)   // "11.8 MB"
    humanFileSize(1234567890) // "1.15 GB"
    

    【讨论】:

    • 使用 toFixed 将其转换为字符串,因此您的回合是字符串或数字。这是不好的做法,您可以轻松地将其转换回数字:+num.tofixed(2)
    • .toPrecision(3) 不涵盖所有这些情况吗?哦..我猜它不涵盖 1000 到 1023 之间。无赖。
    • 它为10130 输入显示9.9,但应该显示9.89。对于10239 - 10.0,但应该是9.99。 (Win 10 资源管理器行为)
    • humanFileSize(10000000000000000000000000000) -&gt; 8.08 undefinedB 啊我最喜欢的字节
    • 最封闭Windows资源管理器格式功能:gist.github.com/AlttiRi/ee82de3728624f997b38e4fb90906914
    【解决方案10】:

    从 2020 年起,您可以使用文件大小的 npm 包,它支持 IEC(默认 1024 次幂)、SI(1000 次幂)和 JEDEC(替代 SI 单位表示法)格式。

    npm install file-size
    
    import filesize from "filesize";
    
    // outputs: 186.46 MB
    filesize(186457865).human('si');
    
    // outputs: 177.82 MiB
    filesize(186457865).human();
    

    https://www.npmjs.com/package/file-size

    【讨论】:

      【解决方案11】:

      我的回答可能会迟到,但我想它会对某人有所帮助。

      指标前缀:

      /**
       * Format file size in metric prefix
       * @param fileSize
       * @returns {string}
       */
      const formatFileSizeMetric = (fileSize) => {
        let size = Math.abs(fileSize);
      
        if (Number.isNaN(size)) {
          return 'Invalid file size';
        }
      
        if (size === 0) {
          return '0 bytes';
        }
      
        const units = ['bytes', 'kB', 'MB', 'GB', 'TB'];
        let quotient = Math.floor(Math.log10(size) / 3);
        quotient = quotient < units.length ? quotient : units.length - 1;
        size /= (1000 ** quotient);
      
        return `${+size.toFixed(2)} ${units[quotient]}`;
      };
      

      二进制前缀:

      /**
       * Format file size in binary prefix
       * @param fileSize
       * @returns {string}
       */
      const formatFileSizeBinary = (fileSize) => {
        let size = Math.abs(fileSize);
      
        if (Number.isNaN(size)) {
          return 'Invalid file size';
        }
      
        if (size === 0) {
          return '0 bytes';
        }
      
        const units = ['bytes', 'kiB', 'MiB', 'GiB', 'TiB'];
        let quotient = Math.floor(Math.log2(size) / 10);
        quotient = quotient < units.length ? quotient : units.length - 1;
        size /= (1024 ** quotient);
      
        return `${+size.toFixed(2)} ${units[quotient]}`;
      };
      

      示例:

      // Metrics prefix
      formatFileSizeMetric(0)      // 0 bytes
      formatFileSizeMetric(-1)     // 1 bytes
      formatFileSizeMetric(100)    // 100 bytes
      formatFileSizeMetric(1000)   // 1 kB
      formatFileSizeMetric(10**5)  // 10 kB
      formatFileSizeMetric(10**6)  // 1 MB
      formatFileSizeMetric(10**9)  // 1GB
      formatFileSizeMetric(10**12) // 1 TB
      formatFileSizeMetric(10**15) // 1000 TB
      
      // Binary prefix
      formatFileSizeBinary(0)     // 0 bytes
      formatFileSizeBinary(-1)    // 1 bytes
      formatFileSizeBinary(1024)  // 1 kiB
      formatFileSizeBinary(2048)  // 2 kiB
      formatFileSizeBinary(2**20) // 1 MiB
      formatFileSizeBinary(2**30) // 1 GiB
      formatFileSizeBinary(2**40) // 1 TiB
      formatFileSizeBinary(2**50) // 1024 TiB
      

      【讨论】:

        【解决方案12】:

        这是我的 - 也适用于非常大的文件 -_-

        function formatFileSize(size)
        {
            var sizes = [' Bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB'];
            for (var i = 1; i < sizes.length; i++)
            {
                if (size < Math.pow(1024, i)) return (Math.round((size/Math.pow(1024, i-1))*100)/100) + sizes[i-1];
            }
            return size;
        }
        

        【讨论】:

        • 它结合了循环和指数运算的性能影响,同时非常难以阅读。我真的不明白这一点。
        • 那就别用了。这只是使用的客户端 cpu,所以谁在乎;)
        • @fiffy 好吧,客户端 CPU 也很宝贵,尤其是在移动设备和复杂应用程序上。 :)
        【解决方案13】:

        基于cocco's answer,但略微去糖化(老实说,我很满意的保留/添加)并且不显示尾随零但仍然支持 0,希望对其他人有用:

        function fileSizeSI(size) {
            var e = (Math.log(size) / Math.log(1e3)) | 0;
            return +(size / Math.pow(1e3, e)).toFixed(2) + ' ' + ('kMGTPEZY'[e - 1] || '') + 'B';
        }
        
        
        // test:
        document.write([0, 23, 4322, 324232132, 22e9, 64.22e12, 76.22e15, 64.66e18, 77.11e21, 22e24].map(fileSizeSI).join('<br>'));

        【讨论】:

          【解决方案14】:

          这里有很多很棒的答案。但是,如果您正在寻找一种非常简单的方法,并且您不介意流行的库,那么一个很好的解决方案是 filesize https://www.npmjs.com/package/filesize

          它有很多选项,用法很简单,例如

          filesize(265318); // "259.1 KB"
          

          取自他们的优秀例子

          【讨论】:

            【解决方案15】:
            1551859712 / 1024 = 1515488
            1515488 / 1024 = 1479.96875
            1479.96875 / 1024 = 1.44528198242188
            

            您的解决方案是正确的。要意识到的重要一点是,为了从15518597121.5,您必须除以 1000,但字节数以 1024 的二进制到十进制块计算,因此 Gigabyte 值较小。

            【讨论】:

            • @Eli... 是的,看起来是这样。我想我从 1551859712 开始就期待“1.5”,但这意味着我是十进制而不是二进制。
            【解决方案16】:

            我发现@cocco's answer 很有趣,但有以下问题:

            1. Don't modify native types 或您不拥有的类型
            2. 为人类编写干净、可读的代码,让压缩器为机器优化代码
            3. (TypeScript 用户的奖励)不能很好地使用 TypeScript

            TypeScript:

             /**
             * Describes manner by which a quantity of bytes will be formatted.
             */
            enum ByteFormat {
              /**
               * Use Base 10 (1 kB = 1000 bytes). Recommended for sizes of files on disk, disk sizes, bandwidth.
               */
              SI = 0,
              /**
               * Use Base 2 (1 KiB = 1024 bytes). Recommended for RAM size, size of files on disk.
               */
              IEC = 1
            }
            
            /**
             * Returns a human-readable representation of a quantity of bytes in the most reasonable unit of magnitude.
             * @example
             * formatBytes(0) // returns "0 bytes"
             * formatBytes(1) // returns "1 byte"
             * formatBytes(1024, ByteFormat.IEC) // returns "1 KiB"
             * formatBytes(1024, ByteFormat.SI) // returns "1.02 kB"
             * @param size The size in bytes.
             * @param format Format using SI (Base 10) or IEC (Base 2). Defaults to SI.
             * @returns A string describing the bytes in the most reasonable unit of magnitude.
             */
            function formatBytes(
              value: number,
              format: ByteFormat = ByteFormat.SI
            ) {
              const [multiple, k, suffix] = (format === ByteFormat.SI
                ? [1000, 'k', 'B']
                : [1024, 'K', 'iB']) as [number, string, string]
              // tslint:disable-next-line: no-bitwise
              const exp = (Math.log(value) / Math.log(multiple)) | 0
              // or, if you'd prefer not to use bitwise expressions or disabling tslint rules, remove the line above and use the following:
              // const exp = value === 0 ? 0 : Math.floor(Math.log(value) / Math.log(multiple)) 
              const size = Number((value / Math.pow(multiple, exp)).toFixed(2))
              return (
                size +
                ' ' +
                (exp 
                   ? (k + 'MGTPEZY')[exp - 1] + suffix 
                   : 'byte' + (size !== 1 ? 's' : ''))
              )
            }
            
            // example
            [0, 1, 1024, Math.pow(1024, 2), Math.floor(Math.pow(1024, 2) * 2.34), Math.pow(1024, 3), Math.floor(Math.pow(1024, 3) * 892.2)].forEach(size => {
              console.log('Bytes: ' + size)
              console.log('SI size: ' + formatBytes(size))
              console.log('IEC size: ' + formatBytes(size, 1) + '\n')
            });
            

            【讨论】:

              【解决方案17】:

              用于 SI 系统的简单而简短的“Pretty Bytes”函数,没有不必要的小数舍入。

              事实上,因为数字大小应该是人类可读的,所以“千分之一”显示不再是人类。

              小数位数默认为 2,但可以在调用函数时将其修改为其他值。常见的主要显示是默认的小数点后2位。

              代码很短,使用了Number String Triplets的方法。

              // Simple Pretty Bytes with SI system
              // Without fraction rounding
              
              function numberPrettyBytesSI(Num=0, dec=2){
              if (Num<1000) return Num+" Bytes";
              Num =("0".repeat((Num+="").length*2%3)+Num).match(/.{3}/g);
              return Number(Num[0])+"."+Num[1].substring(0,dec)+" "+"  kMGTPEZY"[Num.length]+"B";
              }
              
              console.log(numberPrettyBytesSI(0));
              console.log(numberPrettyBytesSI(500));
              console.log(numberPrettyBytesSI(1000));
              console.log(numberPrettyBytesSI(15000));
              console.log(numberPrettyBytesSI(12345));
              console.log(numberPrettyBytesSI(123456));
              console.log(numberPrettyBytesSI(1234567));
              console.log(numberPrettyBytesSI(12345678));

              【讨论】:

                【解决方案18】:

                这是mpen answer的大小改进

                function humanFileSize(bytes, si=false) {
                  let u, b=bytes, t= si ? 1000 : 1024;     
                  ['', si?'k':'K', ...'MGTPEZY'].find(x=> (u=x, b/=t, b**2<1));
                  return `${u ? (t*b).toFixed(1) : bytes} ${u}${!si && u ? 'i':''}B`;    
                }
                

                function humanFileSize(bytes, si=false) {
                  let u, b=bytes, t= si ? 1000 : 1024;     
                  ['', si?'k':'K', ...'MGTPEZY'].find(x=> (u=x, b/=t, b**2<1));
                  return `${u ? (t*b).toFixed(1) : bytes} ${u}${!si && u ? 'i':''}B`;    
                }
                
                
                // TEST
                console.log(humanFileSize(5000));      // 4.9 KiB
                console.log(humanFileSize(5000,true)); // 5.0 kB

                【讨论】:

                  【解决方案19】:

                  对于那些使用Angular 的人,有一个名为angular-pipes 的包有一个管道:

                  文件

                  import { BytesPipe } from 'angular-pipes';
                  

                  用法

                  {{ 150 | bytes }} <!-- 150 B -->
                  {{ 1024 | bytes }} <!-- 1 KB -->
                  {{ 1048576 | bytes }} <!-- 1 MB -->
                  {{ 1024 | bytes: 0 : 'KB' }} <!-- 1 MB -->
                  {{ 1073741824 | bytes }} <!-- 1 GB -->
                  {{ 1099511627776 | bytes }} <!-- 1 TB -->
                  {{ 1073741824 | bytes : 0 : 'B' : 'MB' }} <!-- 1024 MB -->
                  

                  Link to the docs.

                  【讨论】:

                    【解决方案20】:

                    让字节 = 1024 * 10 * 10 * 10;

                    console.log(getReadableFileSizeString(bytes))

                    将返回 1000.0Кб 而不是 1MB

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2014-02-04
                      • 1970-01-01
                      • 1970-01-01
                      • 2017-08-09
                      • 1970-01-01
                      相关资源
                      最近更新 更多