Home → Convert 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
