const formatSize=(size)=>{
if (size < 1024) {
return size + "b";
} else if (size < 1024 * 1024) {
return (size / 1024).toFixed(2) + "KB";
} else if (size < 1024 * 1024 * 1024) {
return (size / (1024 * 1024)).toFixed(2) + "MB";
} else {
return (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
}
}
// 示例用法
console.log(formatSize(500)); // 输出 "500B"
console.log(formatSize(1500)); // 输出 "1.46KB" (约1.46千字节)
console.log(formatSize(2000000)); // 输出 "1.91MB" (约1.91兆字节)
console.log(formatSize(3000000000)); // 输出 "2.79GB" (约2.79千兆字节,即2.79千兆字节)
标签:1024,格式化,log,js,return,内存,console,formatSize,size
From: https://www.cnblogs.com/guangdelw/p/17606646.html