Format Size to KB, MB, GB, TB, PB - Node.js Number

Node.js examples for Number:Int

Description

Format Size to KB, MB, GB, TB, PB

Demo Code

function formatSize(bytes,zeroToEmpty,type)
{
  if (bytes==0)// w  w w .  jav a  2s  .  c  om
  {
    if (zeroToEmpty==true)
    {
      return "";
    }
    else
    {
      if (type=="speed")
      {
        return "0.00 KB/s";
      }
      else
        return "0.00";
    }
  }
  var r = "";
  var u = "KB";
  if (bytes < 1000 * 1024)
  {
    r = (bytes / 1024);
    u = "KB";
  }    
  else if (bytes < 1000 * 1048576)
  {
    r = (bytes / 1048576);
    u = "MB";
  }
  else if (bytes < 1000 * 1073741824)
  {
    r = (bytes / 1073741824);
    u = "GB";
  }
  else if (bytes < 1000 * 1099511627776)
  {
    r = (bytes / 1099511627776);
    u = "TB";
  }
  else
  {
    r = (bytes / 1125899906842624);
    u = "PB";
  }
  
  if (type=="speed")
  {
    u+="/s";
  }
  
  return (r.formatNumber("###,###,###,###.00 ")+u);
}

Related Tutorials