js字节转换、字节格式化函数

有时候在上传附件后需要显示大小,可以选择在后台处理,也可以在前台用js处理。

比如我们想1024MB转换成1GB,那就需要进行转换,这里只是介绍用js进行转换。

function bytesToSize(bytes) {  
  if (bytes === 0) return '0 B';
  var k = 1024;
  sizes = ['B','KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  i = Math.floor(Math.log(bytes) / Math.log(k))  
  //
return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
  return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
  //toPrecision(3) 后面保留两位小数,如1.00GB
} 
原文地址:https://www.cnblogs.com/sysg/p/6554791.html