Explain Codes LogoExplain Codes Logo

Correct way to convert size in bytes to KB, MB, GB in JavaScript

javascript
prompt-engineering
functions
performance
Alex KataevbyAlex Kataev·Jan 24, 2025
TLDR
function bytesToSize(bytes, precision = 2) { if (bytes === 0) return '0 Bytes'; const units = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const index = Math.floor(Math.log(bytes) / Math.log(1024)); return (bytes / (1024 ** index)).toFixed(precision) + ' ' + units[index]; } // Example console.log(bytesToSize(1024)); // "1.00 KB"

bytesToSize instantly converts bytes to a human-readable size. Configure the precision with the second argument and get the fitting unit without the headache.

Edge cases & negative sizes: Be the hero, beat the zero

Not everything comes in neat packages, right? Let's armor our function against non-numeric inputs or a zero byte situtation, and even cater to negative sizes – they might rarely appear, but we don't want a meltdown when the unexpected arrives.

function bytesToSize(bytes, precision = 2) { if (typeof bytes !== 'number' || isNaN(bytes)) throw new Error('Input must be a number...'); const sign = bytes < 0 ? '-' : ''; // Hey negatives, we've got you covered! if (bytes === 0) return '0 Bytes'; // Tada! Zero, the hero bytes = Math.abs(bytes); const units = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const index = Math.floor(Math.log(bytes) / Math.log(1024)); return sign + (bytes / (1024 ** index)).toFixed(precision) + ' ' + units[index]; }

Advanced formatting options: Bits, bytes, SI or IEC units

Let's present the liberty of choosing for our users by introducing different bases and even a choice between SI and IEC unit systems. After all, who doesn't love customizable settings?

function bytesToSize(bytes, precision = 2, useSI = false) { if (bytes === 0) return '0 Bytes'; const factor = useSI ? 1000 : 1024; // User desiring SI? No problemo! const units = useSI ? ['Bytes', 'KB', 'MB', 'GB', 'TB'] : ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB']; // The secret sauce of unit selection const index = Math.floor(Math.log(bytes) / Math.log(factor)); return (bytes / factor ** index).toFixed(precision) + ' ' + units[index]; }

Minified version: Good things come in small packages!

Time to embrace our inner minimalist. A minified version always comes in handy when bytes are precious.

const bTS=(b,p=2)=>(b===0?'0 Bytes':((u=['Bytes','KB','MB','GB','TB']),(i=Math.floor(Math.log(b)/Math.log(1024))),((b/(1024**i)).toFixed(p)+' '+u[i])));

Raw data needs love too: Don't format everything

Sometimes, what you really need is the exact byte count. So let's switch off formatting when the raw, unadulterated data is the true requirement.

Quick and dirty: Simplify with a one-liner

Looking for a fast way to toss around byte sizes on your console or a quick handy tool for inline scripts? Voila, presenting the compact yet powerful one-liner.

const bToS = b => b === 0 ? '0 Bytes' : ((u = ['Bytes','KB','MB','GB','TB']), (i = Math.floor(Math.log(b) / Math.log(1024))), ((b / (1024 ** i)).toFixed(2) + ' ' + u[i]));

Scale it up: Expand your horizons

In the world of big data, terabytes may seem like coins. So why not step it up a notch? Just add extra units to your array and make your function future-proof.