简体   繁体   中英

How do I convert file size to mb only in JavaScript?

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.

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

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" ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM