/**
* 转换文件大小单位
*
* @param {number} bytes - 文件大小(字节)
* @param {number} [decimalPlaces=2] - 小数点后保留的位数(默认为2)
* @returns {string} 转换后的文件大小字符串,如 "1.23 MB"
*/
function formatFileSize(bytes, decimalPlaces = 2) {
if (bytes === 0) return '0 Bytes'; // 如果字节数为0,直接返回 "0 Bytes"
// 定义单位数组和对应的字节数(以1024为基准的进位)
const units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
let unitIndex = 0;
// 循环直到找到合适的单位(即 bytes 小于 1024 的下一个单位)
while (bytes >= 1024 && unitIndex < units.length - 1) {
bytes /= 1024; // 除以1024,进位到下一个单位
unitIndex++; // 单位索引加1
}
// 使用 toFixed 方法将浮点数格式化为指定小数位数的字符串
// 注意:toFixed 方法会返回字符串,而不是数字
const formattedSize = bytes.toFixed(decimalPlaces);
// 返回转换后的文件大小字符串和单位
return `${formattedSize} ${units[unitIndex]}`;
}
// 示例用法:
console.log(formatFileSize(1024)); // 输出 "1.00 KB"
console.log(formatFileSize(1048576)); // 输出 "1.00 MB"
console.log(formatFileSize(1073741824)); // 输出 "1.00 GB"
console.log(formatFileSize(0)); // 输出 "0 Bytes"
这个函数接受两个参数:bytes
(文件大小,以字节为单位)和decimalPlaces
(可选,小数点后保留的位数,默认为2)。函数首先检查字节数是否为0,如果是,则直接返回 "0 Bytes"。然后,它使用一个循环来确定适当的单位,并将字节数除以1024以进位到下一个单位,直到字节数小于1024或达到单位数组的最大长度。最后,它使用 toFixed
方法将浮点数格式化为字符串,并返回转换后的文件大小字符串和单位。