Converting file size in bytes to human-readable string

后端 未结 19 2034
眼角桃花
眼角桃花 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:24

    This is size improvement of 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

提交回复
热议问题