Friday, May 10, 2024

How to convert Bytes to Size in Javascript

 Javascript

function readableBytes(bytes) {

    if(typeof(bytes) == "undefined" || bytes == 0 || bytes == '') return '0 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];

}