Skip to content

Instantly share code, notes, and snippets.

@Noitidart
Created May 2, 2019 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Noitidart/0a0e12c3a1111ebc681b424285b00b39 to your computer and use it in GitHub Desktop.
Save Noitidart/0a0e12c3a1111ebc681b424285b00b39 to your computer and use it in GitHub Desktop.
/**
* Convert a file size given in bytes to human readable sizes.
* Source: https://stackoverflow.com/a/18650828/1828637
*
* @param {number} bytes
* @param {number} decimals - Should be >= 0, if less than 0 it is adjusted to 0.
*/
function 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];
}
export {
formatBytes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment