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

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

Published: 11/12/2022

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

About Code with Node.js

This is a personal blog and reference point of a Node.js developer.

I write and explain how different Node and JavaScript aspects work, as well as research popular and cool packages, and of course fail time to time.