sizeformat.ts 801 B

1234567891011121314151617181920212223242526272829303132
  1. /**
  2. * Format bytes as human-readable text.
  3. *
  4. * @param bytes Number of bytes.
  5. * @param si True to use metric (SI) units, aka powers of 1000. False to use
  6. * binary (IEC), aka powers of 1024.
  7. * @param dp Number of decimal places to display.
  8. *
  9. * @return Formatted string.
  10. */
  11. export const humanFileSize = (bytes: number, si=false, dp=1): string => {
  12. const threshold = si ? 1000 : 1024;
  13. if (Math.abs(bytes) < threshold) {
  14. return bytes + ' B';
  15. }
  16. const units = si
  17. ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  18. : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
  19. let u = -1;
  20. const r = 10**dp;
  21. do {
  22. bytes /= threshold;
  23. ++u;
  24. } while (Math.round(Math.abs(bytes) * r) / r >= threshold && u < units.length - 1);
  25. return bytes.toFixed(dp) + ' ' + units[u];
  26. }