Created
May 2, 2019 03:22
-
-
Save Noitidart/0a0e12c3a1111ebc681b424285b00b39 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* 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