common.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * 生成UUID
  3. */
  4. export function getUUID(): string {
  5. const len = 32; // 32长度
  6. let radix = 16; // 16进制
  7. const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  8. const uuid = [];
  9. radix = radix || chars.length;
  10. if (len) {
  11. for (let i = 0; i < len; i++) {
  12. uuid[i] = chars[0 | (Math.random() * radix)];
  13. }
  14. } else {
  15. let r;
  16. uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
  17. uuid[14] = '4';
  18. for (let j = 0; j < 36; j++) {
  19. if (!uuid[j]) {
  20. r = 0 | (Math.random() * 16);
  21. uuid[j] = chars[j === 19 ? (r & 0x3) | 0x8 : r];
  22. }
  23. }
  24. }
  25. return uuid.join('');
  26. }
  27. /**
  28. * 更换数字单位
  29. * @param value
  30. * @param decimals
  31. * @returns
  32. */
  33. export function changeUnit(value: number, decimals = 3): string {
  34. let base = 1000;
  35. const newValue = ['', '', ''];
  36. let num = 3;
  37. while (value / base >= 1) {
  38. base *= 10;
  39. num += 1;
  40. }
  41. if (num <= 4) {
  42. newValue[1] = '千';
  43. newValue[0] = parseInt((value / 1000).toFixed(decimals)) + '';
  44. } else if (num <= 8) {
  45. // 万
  46. const text1 = parseInt((num - 4).toFixed(decimals)) / 3 > 1 ? '千万' : '万';
  47. const fm = '万' === text1 ? 10000 : 10000000;
  48. newValue[1] = text1;
  49. newValue[0] = value / fm + '';
  50. } else if (num <= 16) {
  51. // 亿
  52. let text1 = (num - 8) / 3 > 1 ? '千亿' : '亿';
  53. text1 = (num - 8) / 4 > 1 ? '万亿' : text1;
  54. text1 = (num - 8) / 7 > 1 ? '千万亿' : text1;
  55. let fm = 1;
  56. if ('亿' === text1) {
  57. fm = 100000000;
  58. } else if ('千亿' === text1) {
  59. fm = 100000000000;
  60. } else if ('万亿' === text1) {
  61. fm = 1000000000000;
  62. } else if ('千万亿' === text1) {
  63. fm = 1000000000000000;
  64. }
  65. newValue[1] = text1;
  66. newValue[0] = (value / fm).toFixed(decimals) + '';
  67. }
  68. if (value < 1000) {
  69. newValue[1] = '';
  70. newValue[0] = value + '';
  71. }
  72. return newValue.join('');
  73. }