Skip to content

Instantly share code, notes, and snippets.

@alekstar79
Last active May 24, 2024 17:14
Show Gist options
  • Save alekstar79/e55c9117a02ca90f08b37eeee8adca03 to your computer and use it in GitHub Desktop.
Save alekstar79/e55c9117a02ca90f08b37eeee8adca03 to your computer and use it in GitHub Desktop.
Calculating and formatting file size
/**
* @param {Number} bytes
* @param {Number} decimals
* @return {string}
*/
export function format(bytes, decimals = 2)
{
if (bytes === 0) return '0 B'
const dim = ['B','KB','MB','GB','TB','PB','EB','ZB','YB'],
d = decimals < 0 ? 0 : decimals,
k = 1024,
i = Math.floor(Math.log(bytes) / Math.log(k)),
size = parseFloat((bytes / k ** i)
.toFixed(d))
return size + ' ' + dim[i]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment