Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert kilobytes to megabytes in javascript [duplicate]

Tags:

javascript

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

like image 554
Krishnan-777 Avatar asked Jan 06 '23 14:01

Krishnan-777


1 Answers

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));
like image 133
Thanga Avatar answered Jan 11 '23 22:01

Thanga