ygoa.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. export function convertToChineseCurrency(amount) {
  2. if (amount === "0" || amount === 0) {
  3. return "零元整";
  4. }
  5. const CN_NUMS = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
  6. const CN_INT = ["", "拾", "佰", "千"];
  7. const CN_UNIT = ["", "万", "亿", "兆"];
  8. const CN_DECIMAL = ["角", "分", "厘", "毫"];
  9. // 将金额转换为字符串并去掉多余的零
  10. let str = amount.toString().replace(/[^0-9.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./, '').replace('$#$', '.');
  11. let [integerPart, decimalPart] = str.split('.');
  12. // 处理整数部分
  13. let integerLen = integerPart.length;
  14. let integerResult = '';
  15. let zeroCount = 0; // 记录连续的零
  16. for (let i = 0; i < integerLen; i++) {
  17. let num = integerPart.charAt(i);
  18. let unitPos = integerLen - i - 1;
  19. let unitIndex = unitPos % 4;
  20. // 当前位为零时不进行处理
  21. if (num === '0') {
  22. zeroCount++;
  23. } else {
  24. if (zeroCount > 0) {
  25. integerResult += CN_NUMS[0];
  26. }
  27. zeroCount = 0;
  28. integerResult += CN_NUMS[parseInt(num)] + CN_INT[unitIndex];
  29. }
  30. if (unitIndex === 0) {
  31. integerResult += CN_UNIT[Math.floor(unitPos / 4)];
  32. }
  33. }
  34. // 处理小数部分
  35. let decimalResult = '';
  36. if (decimalPart) {
  37. let decimalLen = decimalPart.length;
  38. for (let i = 0; i < decimalLen; i++) {
  39. let num = decimalPart.charAt(i);
  40. if (num !== '0') {
  41. decimalResult += CN_NUMS[parseInt(num)] + CN_DECIMAL[i];
  42. }
  43. }
  44. }
  45. if (!decimalResult) {
  46. decimalResult = '整';
  47. }
  48. return integerResult + decimalResult;
  49. }