file.ts 604 B

1234567891011121314151617181920
  1. /**
  2. * Formats a byte count into a human-readable string (e.g. `1.5 MB`).
  3. *
  4. * @param bytes - The number of bytes to format.
  5. * @returns A formatted string with the appropriate unit (B, KB, MB, GB, or TB).
  6. */
  7. export function formatFileSize(bytes: number): string {
  8. if (bytes === 0) return '0 B';
  9. const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  10. const k = 1024;
  11. const i = Math.floor(Math.log(bytes) / Math.log(k));
  12. const size = bytes / Math.pow(k, i);
  13. // No decimals for bytes, 1 decimal for larger units
  14. return i === 0
  15. ? `${size} ${units[i]}`
  16. : `${size.toFixed(1)} ${units[i]}`;
  17. }