Converting file size in bytes to human-readable string

后端 未结 19 2145
眼角桃花
眼角桃花 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条回答
  •  猫巷女王i
    2020-11-28 18:18

    A simple and short "Pretty Bytes" function for the SI system without the unnecessary fractionals rounding.

    In fact, because the number size is supposed to be human-readable, a "1 of a thousand fraction" display is no longer human.

    The number of decimal places is defaulted to 2 but can be modified on calling the function to other values. The common mostly display is the default 2 decimal place.

    The code is short and uses the method of Number String Triplets.

    Hope it is useful and a good addition to the other excellent codes already posted here.

    // 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));

提交回复
热议问题