How do I convert file size to mb only in JavaScript?
var sizeInMB = (sizeInBytes / (1024*1024)).toFixed(2);alert(sizeInMB + 'MB');
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 exactly digits after the decimal place, 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));
- Details on Number.prototype.toFixed().
- Below you can view file size conversion table, for future help.Conversion table