32

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.

jgillich
  • 71,459
  • 6
  • 57
  • 85
  • How about just figuring out how many bytes there are in a megabyte (1 048 576) and use basic math to calculate the number you are looking for. Search for javascripts math methods and I'm sure you'll figure it out, it's pretty simple stuff. – adeneo Dec 12 '11 at 08:11
  • 2
    @adeneo "pretty simple stuff" are famous last words. Something like fuzzy time ala jquery.timeago.js would be useful. – Leif Gruenwoldt Jan 04 '12 at 20:44
  • 1
    @leif81 Got here looking for exactly that... – Tim Sylvester Jan 28 '12 at 23:53

3 Answers3

78
var sizeInMB = (sizeInBytes / (1024*1024)).toFixed(2);
alert(sizeInMB + 'MB');
devnull69
  • 16,402
  • 8
  • 50
  • 61
  • 1
    var sizeInMB = $([sizeInBytes]).map(function(){return (this/1024/1024).toFixed(2) })[0] – Tim Sylvester Jan 28 '12 at 23:52
  • Also check out [Correct way to convert size in bytes to KB, MB, GB in Javascript](http://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript) – Eugene van der Merwe Mar 17 '16 at 08:31
16

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));
  1. Details on Number.prototype.toFixed().
  2. Below you can view file size conversion table, for future help. Conversion table
Azeem Mirza
  • 161
  • 1
  • 2
2

Only to MB + Multipurpose bytes converter to KB, MB, GB

function byteConverter( bytes, decimals, only) {
    const K_UNIT = 1024;
    const SIZES = ["Bytes", "KB", "MB", "GB", "TB", "PB"];

    if(bytes== 0) return "0 Byte";
  
    if(only==="MB") return (bytes / (K_UNIT*K_UNIT)).toFixed(decimals) + " MB" ;
  
    let i = Math.floor(Math.log(bytes) / Math.log(K_UNIT));
    let resp = parseFloat((bytes / Math.pow(K_UNIT, i)).toFixed(decimals)) + " " + SIZES[i];
  
    return resp;
}


let bytesInput = 2100050090;
console.log(byteConverter(bytesInput, 2));
console.log(byteConverter(bytesInput, 2, "MB" ));
GMKHussain
  • 3,342
  • 1
  • 21
  • 19