Created
November 6, 2018 14:11
-
-
Save RomiC/792e5eff7cb99cd2b24239068a6054dd to your computer and use it in GitHub Desktop.
Format size in human-readable way
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
/** | |
* Format size in bytes in a human-readable way | |
* Examples: | |
* - humanReadableBytes(9708) → "9.48 KB" | |
* - humanReadableBytes(9708098213) → "9.04 GB" | |
* @param bytes Amount in bytes | |
* @return Formatted price | |
*/ | |
function humanReadableSize(bytes: number): string { | |
const names: string[] = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; | |
let rest = bytes; | |
for (const size in names) { | |
if (rest > 1024) { | |
rest = Number((rest / 1024).toPrecision(3)); | |
} else { | |
return `${rest} ${names[size]}`; | |
} | |
} | |
return `${rest} ${names[names.length - 1]}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment