Last active
May 24, 2024 17:14
-
-
Save alekstar79/e55c9117a02ca90f08b37eeee8adca03 to your computer and use it in GitHub Desktop.
Calculating and formatting file size
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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