format.ts 884 B

123456789101112131415161718192021222324252627282930313233343536
  1. /*
  2. * Formats a number with comma separators.
  3. formatNumber(1234567) will return '1,234,567'
  4. formatNumber(1234567.89) will return '1,234,567.89'
  5. */
  6. export const formatNumber = (num: number | string) => {
  7. if (!num)
  8. return num
  9. const parts = num.toString().split('.')
  10. parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  11. return parts.join('.')
  12. }
  13. export const formatFileSize = (num: number) => {
  14. if (!num)
  15. return num
  16. const units = ['', 'K', 'M', 'G', 'T', 'P']
  17. let index = 0
  18. while (num >= 1024 && index < units.length) {
  19. num = num / 1024
  20. index++
  21. }
  22. return `${num.toFixed(2)}${units[index]}B`
  23. }
  24. export const formatTime = (num: number) => {
  25. if (!num)
  26. return num
  27. const units = ['sec', 'min', 'h']
  28. let index = 0
  29. while (num >= 60 && index < units.length) {
  30. num = num / 60
  31. index++
  32. }
  33. return `${num.toFixed(2)} ${units[index]}`
  34. }