Skip to content

formatFileSize

文件大小转换

配置项

参数类型是否必选默认值参数描述
bytesnumber-文件大小,单位为字节

返回值

类型描述
string格式化后的文件大小字符串

示例

formatFileSize(1024) // '1.00 KB'

源码

js
export function formatFileSize(bytes) {
    const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
    let index = 0;
    while (bytes >= 1024 && index < units.length - 1) {
        bytes /= 1024;
        index++;
    }
    return bytes.toFixed(2) + ' ' + units[index];
}