Convert bytes to megabytes, gigabytes, terabytes without a loop.

What if I tell you you can convert bytes to petabytes without doing a loop and constantly dividing by 1024?

function bytesToHuman(bytes) {
    let prefixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    let base = 1024;
    let cl = Math.min(parseInt(Math.log(bytes) / Math.log(base), 10), prefixes.length - 1);    
    return (bytes / Math.pow(base, cl)).toFixed(2) + ' ' + prefixes[cl];

console.log(bytesToHuman(1024 * 1024 * 10)); // 10.00 MB
console.log(bytesToHuman(2151099283)); // 2.00 GB

Did you know that I made an in-browser image converter, where you can convert your images without uploading them anywhere? Try it out and let me know what you think. It's free.

Leave a Comment

Your email address will not be published. Required fields are marked *