Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to convert bytes to KB, MB and GB

Short answer

Divide by 1024 until the number becomes less than 1024, and move to the next unit each time:

const formatBytes = (bytes) => {
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let index = 0;
  while (bytes >= 1024 && index < units.length - 1) {
    bytes /= 1024;
    index++;
  }
  return `${Number(bytes.toFixed(1))} ${units[index]}`;
};
 
console.log(formatBytes(500));
console.log(formatBytes(1536));
console.log(formatBytes(5368709120));

Output:

500 B
1.5 KB
5 GB

With Intl.NumberFormat

Intl.NumberFormat knows units like kilobyte and megabyte and writes them in the right language:

const format = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'megabyte',
  unitDisplay: 'short',
  maximumFractionDigits: 1,
});
 
console.log(format.format(3.456));

Output:

3.5 MB

Common mistake

toFixed() returns a string, and it keeps a zero at the end. Number() removes it:

console.log((2).toFixed(1), Number((2).toFixed(1)));

Output:

2.0 2

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.