index.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * 折中方案:处理浮点失真,如果页面卡顿,则需要服务处理
  3. * @param val
  4. * @param decimal 需要保留小数位 默认2
  5. * @param maxCount 最大小数位 超过的时候需要对数值进行处理
  6. * @returns
  7. */
  8. export function getDecimalsNum(val: any, decimal = 2, maxCount = 6) {
  9. let result = val
  10. if (typeof val === 'number') {
  11. const str = val.toString();
  12. if (str.includes('.')) {
  13. const num = str.indexOf('.') + 1;
  14. const count = str.length - num;
  15. if (count > maxCount) {
  16. result = val.toFixed(decimal)
  17. }
  18. }
  19. }
  20. return result
  21. }
  22. /**
  23. * 强制保留小数位,零位四舍五入取整
  24. * @param value
  25. * @param decimal 保留小数位 默认2
  26. * @returns
  27. */
  28. export function toDecimalFull(value: number, decimal = 2) {
  29. if (decimal <= 0) {
  30. return Math.round(value).toString();
  31. } else {
  32. let str = value.toString();
  33. const num = str.indexOf('.');
  34. if (num < 0) {
  35. // 小数位自动补零
  36. if (decimal > 0) {
  37. const count = str.length;
  38. str += '.';
  39. while (str.length <= count + decimal) {
  40. str += '0';
  41. }
  42. }
  43. return str;
  44. }
  45. return value.toFixed(decimal);
  46. }
  47. }
  48. /**
  49. * 数字转千位符金额
  50. * @param value 金额数值
  51. * @param decimal 保留小数位 默认2
  52. */
  53. export function formatAmount(value: number, decimal = 2) {
  54. const reg = new RegExp('(\\d)(?=(\\d{3})+$)', 'ig');
  55. const result = value.toFixed(decimal).toString().split('.');
  56. result[0] = result[0].replace(reg, '$1,');
  57. return result.join('.');
  58. }