Home  >  Article  >  Web Front-end  >  js tool function-format file size

js tool function-format file size

巴扎黑
巴扎黑Original
2016-11-25 15:23:591731browse

ES6 code:

function formatFileSize(fileSize, idx = 0) {  
    const units = ["B", "KB", "MB", "GB"];  
    if (fileSize < 1024 || idx === units.length - 1) {  
        return fileSize.toFixed(1) + units[idx];  
    }  
    return formatFileSize(fileSize / 1024, ++idx);  
}



Old version code:

function formatFileSize(fileSize, idx) {  
    var units = ["B", "KB", "MB", "GB"];  
    idx = idx || 0;  
    if (fileSize < 1024 || idx === units.length - 1) {  
        return fileSize.toFixed(1) + units[idx];  
    }  
    return formatFileSize(fileSize / 1024, ++idx);  
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn