How do I convert file size to MB only in JavaScript, It comes back as a long INT sometimes and I would like to convert this to a MB instead of it showing bytes or kb.
If possible I would like too also make it show as result like this example("0.01MB"), if it is under the 1 MB.
The formatFileSize() function converts the size from bytes to KB, MB, GB, TB, PB, EB, ZB, YB using Javascript. The formatFileSize() function accepts the following parametters.
You can retrieve the length of the file with File#length(), which will return a value in bytes, so you need to divide this by 1024*1024 to get its value in mb.
The quick and easy method to convert between size units To convert smaller units to larger units (convert bytes to kilobytes or megabytes) you simply divide the original number by 1,024 for each unit size along the way to the final desired unit.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With