Categories
JavaScript Answers

How to Convert Size in Bytes to KB, MB, GB in JavaScript?

Spread the love

Sometimes, we get a number in bytes, and we want to convert it to KB, MB, or GB.

We can do that easily with JavaScript.

In this article, we’ll look at how to convert a byte number to KB, MB, or GB with JavaScript.

Convert Size in Bytes to KB, MB, GB in JavaScript

We can convert a number in bytes to KB, MB, and GB easily with our own JavaScript function.

To create our own function, we write:

const formatBytes = (bytes, decimals = 2) => {
  if (bytes === 0) {
    return '0 Bytes';
  }
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

console.log(formatBytes(1024))
console.log(formatBytes(1024 * 1024))

We create the formatBytes function that takes the number of bytes and the number of decimals to round the number to.

First we check if bytes is 0.

If it is, we return '0 bytes' .

Next, we create the k constant to set the number of bytes in a kilobyte.

This lets us convert the number of bytes to what we want easily.

dm is the number of decimal places to round to.

We have the sizes array with the units to append to the converted number.

i is the exponent with base kthat’s raised to convert to the number of bytes when we have the number of KB, MB, GB, etc.

This is also the same as the index we use to pick the right unit from the sizes .

Finally, we convert the number of bytes to the unit we want by diving the number of byts by k raised to the power of i .

The number is rounded to the number of decimal places we want with toFixed .

toFixed returns a string with the rounded number in it.

And then we concatenate the string with sizes[1] .

Therefore, the first console log logs '1 KB' .

And the 2nd console log logs '1 MB' .

Conclusion

We can convert the number of bytes to the unit we want easily with math methods that are built into the JavaScript standard library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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