How to convert file size to mb only in JavaScript?

How to convert the file size to MB only in JavaScript, it sometimes returns as a long INT, and I would like to convert it to MB instead of it, showing bytes or kb.

If possible, I would also like to show a result like this example ("0.01MB") if it is less than 1 MB.

+8
source share
2 answers
var sizeInMB = (sizeInBytes / (1024*1024)).toFixed(2); alert(sizeInMB + 'MB'); 
+31
source

Javscript ES5 or earlier:

 function bytesToMegaBytes(bytes) { return bytes / (1024*1024); } 

Javscript ES6 (arrow functions):

 const bytesToMegaBytes = bytes => bytes / (1024*1024); 

If you want to round to digits after the decimal point, then:

 function (bytes, roundTo) { var converted = bytes / (1024*1024); return roundTo ? converted.toFixed(roundTo) : converted; } 

In E6 or beyond:

 const bytesToMegaBytes = (bytes, digits) => roundTo ? (bytes / (1024*1024)).toFixed(digits) : (bytes / (1024*1024)); 
  1. Details on Number.prototype.toFixed () .
  2. Below you can view the file size conversion chart for further assistance. Conversion table
+1
source

Source: https://habr.com/ru/post/903572/


All Articles