Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 434
Webmaster.Gotactics Avatar asked Dec 12 '11 08:12

Webmaster.Gotactics


People also ask

How to convert file size to KB and MB in JavaScript?

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.

How do I convert MB to file size?

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.

How do you change a file size?

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.


2 Answers

var sizeInMB = (sizeInBytes / (1024*1024)).toFixed(2); alert(sizeInMB + 'MB'); 
like image 109
devnull69 Avatar answered Sep 21 '22 10:09

devnull69


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
like image 40
Azeem Mirza Avatar answered Sep 22 '22 10:09

Azeem Mirza