Correct way to convert size in bytes to KB, MB, GB in JavaScript
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.
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?
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.
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.
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.
Was this article helpful?