Skip to content

Instantly share code, notes, and snippets.

@RomiC
Created November 6, 2018 14:11
Show Gist options
  • Save RomiC/792e5eff7cb99cd2b24239068a6054dd to your computer and use it in GitHub Desktop.
Save RomiC/792e5eff7cb99cd2b24239068a6054dd to your computer and use it in GitHub Desktop.
Format size in human-readable way
/**
* 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