4

how to convert 4000 kilobytes to 4 megabytes in javascript?

i have tried

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 byte';}
      return bytes;
}


formatSizeUnits(4000);

Ans I get is "3.91 KB". i need to get 4mb

Krishnan-777
  • 61
  • 1
  • 5
  • 1
    Use `Math.round(bytes/1024)+' KB';` – rrk Feb 25 '16 at 09:43
  • 4000 kilobytes is usually not considered equal to 4MB - though there are exceptions where this applies. If you want your function to be such an exception, replace the divisors with 1000000000, 1000000 and 1000 respectively – david a. Feb 25 '16 at 09:47
  • probably you meant `4kb` instead of `4mb` – rrk Feb 25 '16 at 09:51

1 Answers1

9

Your function is correct. It accepts bytes only. But what your trying to do is formatSizeUnits(4000). this is wrong and the expected output is 3.91 MB as it is divided by 1024 and not with 1000. The correct ways is to call like

 formatSizeUnits(4000*1024)  // beacuse 4000 is in KB and convert into bytes

See the below snippet to get the correct answer

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 byte';}
      return bytes;
}


document.write(formatSizeUnits(4000*1024));
Thanga
  • 7,811
  • 3
  • 19
  • 38