JavaScript - How can I covert bytes to mega bytes?

Paul125
Kilo Guru

I am trying the below code to convert bytes to mb but script returning output in GB.

var bytes = 68718940160;
function readableBytes(bytes) {
var i = Math.floor(Math.log(bytes) / Math.log(1024)),
sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

return (bytes / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
}

Expected output: 68718.94016 MB or rounded value

1 ACCEPTED SOLUTION

Mike Allen
Mega Sage

If all you need is MB forever and ever, just hard code 2 and the Math.pow second parameter and 2 as the size, as 2 is the MB designation in the size array.

 

var bytes = 68718940160;

function readableBytes(bytes) {
var i = Math.floor(Math.log(bytes) / Math.log(1024)),
sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

return (bytes / Math.pow(1024, 2)).toFixed(2) * 1 + ' ' + sizes[2];
}

View solution in original post

4 REPLIES 4

Mike Allen
Mega Sage

If all you need is MB forever and ever, just hard code 2 and the Math.pow second parameter and 2 as the size, as 2 is the MB designation in the size array.

 

var bytes = 68718940160;

function readableBytes(bytes) {
var i = Math.floor(Math.log(bytes) / Math.log(1024)),
sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

return (bytes / Math.pow(1024, 2)).toFixed(2) * 1 + ' ' + sizes[2];
}

Paul125
Kilo Guru

Thanks for the reply Mike. MB is going to be permanent but I am getting 65535.49 MB which not accurate in this case.

*** Script: 65535.49 MB
 

It is accurate.  There are 1024 KB in a MB, not 1000 like you expect in your outcome.

If you are looking for 1000, change the 1024s in the code to 1000 and it will work.