Converting file size in bytes to human-readable string

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

    Based on cocco's answer but slightly desugerified (honestly, ones I was comfortable with are remained/added) and doesn't show trailing zeros but still supports 0, hope to be useful for others:

    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('
    '));

提交回复
热议问题