js中将数字格式化成内存的形式

发布时间 2023-08-04 17:54:34作者: 厚礼蝎
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千兆字节)