猿问

在JavaScript中将字节大小转换为KB,MB,GB的正确方法

我通过PHP 将此代码转换为秘密大小(以字节为单位)。


现在,我想使用JavaScript 将这些尺寸转换为人类可读的尺寸。我试图将此代码转换为JavaScript,如下所示:


function formatSizeUnits(bytes){

  if      (bytes >= 1073741824) { bytes = (bytes / 1073741824).toFixed(2) + " GB"; }

  else if (bytes >= 1048576)    { bytes = (bytes / 1048576).toFixed(2) + " MB"; }

  else if (bytes >= 1024)       { bytes = (bytes / 1024).toFixed(2) + " KB"; }

  else if (bytes > 1)           { bytes = bytes + " bytes"; }

  else if (bytes == 1)          { bytes = bytes + " byte"; }

  else                          { bytes = "0 bytes"; }

  return bytes;

}

这是正确的方法吗?有更容易的方法吗?


海绵宝宝撒
浏览 2225回答 3
3回答

MMTTMM

const units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];function niceBytes(x){&nbsp; let l = 0, n = parseInt(x, 10) || 0;&nbsp; while(n >= 1024 && ++l){&nbsp; &nbsp; &nbsp; n = n/1024;&nbsp; }&nbsp; //include a decimal point and a tenths-place digit if presenting&nbsp;&nbsp; //less than ten of KB or greater units&nbsp; return(n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l]);}结果:niceBytes(1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 1 byteniceBytes(435)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 435 bytesniceBytes(3398)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 3.3 KBniceBytes(490398)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 479 KBniceBytes(6544528)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 6.2 MBniceBytes(23483023)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 22 MBniceBytes(3984578493)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 3.7 GBniceBytes(30498505889)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 28 GBniceBytes(9485039485039445)&nbsp; &nbsp; // 8.4 PB

一只名叫tom的猫

toFixed(n)toPrecision(n)对于所有值都具有一致的精度可能更合适。为了避免尾随零(例如:),bytesToSize(1000) // return "1.00 KB"我们可以使用parseFloat(x)。我建议将最后一行替换为:return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];。与之前的更改相比,结果是:&nbsp;bytesToSize(1000) // return "1 KB"/&nbsp;bytesToSize(1100) // return "1.1 KB"/&nbsp;bytesToSize(1110) // return "1.11 KB/&nbsp;bytesToSize(1111) // also return "1.11 KB"
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答