格式化文件大小
格式化文件大小
方式1:
function formatFileSize(fileSize) {
if (fileSize < 1024) {
return fileSize + 'B';
} else if (fileSize < (1024*1024)) {
var temp = fileSize / 1024;
temp = Math.round(temp);
return temp + 'KB';
} else if (fileSize < (1024*1024*1024)) {
var temp = fileSize / (1024*1024);
temp = Math.round(temp);
return temp + 'MB';
} else {
var temp = fileSize / (1024*1024*1024);
temp = Math.round(temp);
return temp + 'GB';
}
}
方式2:
const formatSize = (bytes: number): string => {
if (bytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
const size = parseFloat((bytes / Math.pow(k, i)).toFixed(2))
return `${size} ${sizes[i]}`
}