Skip to content

Instantly share code, notes, and snippets.

@Ref-Bit
Created December 20, 2020 15:39
Show Gist options
  • Save Ref-Bit/e161817f1507f7db192308bae0d03f98 to your computer and use it in GitHub Desktop.
Save Ref-Bit/e161817f1507f7db192308bae0d03f98 to your computer and use it in GitHub Desktop.
Convert Bytes number into (KB, MB, GB, TB,...) depending on its size.
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];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment