Home > Article > Web Front-end > js tool function-format file size
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); }