Converting file size in bytes to human-readable string

后端 未结 19 2139
眼角桃花
眼角桃花 2020-11-28 17:58

I\'m using this function to convert a file size in bytes to a human-readable file size:

function getReadableFileSizeString(fileSizeInBytes) {
    var i = -1;         


        
19条回答
  •  盖世英雄少女心
    2020-11-28 18:27

    Here is a prototype to convert a number to a readable string respecting the new international standards.

    There are two ways to represent big numbers: You could either display them in multiples of 1000 = 10 3 (base 10) or 1024 = 2 10 (base 2). If you divide by 1000, you probably use the SI prefix names, if you divide by 1024, you probably use the IEC prefix names. The problem starts with dividing by 1024. Many applications use the SI prefix names for it and some use the IEC prefix names. The current situation is a mess. If you see SI prefix names you do not know whether the number is divided by 1000 or 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});
    

    This function contains no loop, and so it's probably faster than some other functions.

    Usage:

    IEC prefix

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

    SI prefix

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

    i set the IEC as default because i always used binary mode to calculate the size of a file... using the power of 1024


    If you just want one of them in a short oneliner function:

    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
    

    Usage:

    console.log(fileSizeIEC(7412834521));
    

    if you have some questions about the functions just ask

提交回复
热议问题