| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- export function convertToChineseCurrency(amount) {
- if (amount === "0" || amount === 0) {
- return "零元整";
- }
- const CN_NUMS = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
- const CN_INT = ["", "拾", "佰", "千"];
- const CN_UNIT = ["", "万", "亿", "兆"];
- const CN_DECIMAL = ["角", "分", "厘", "毫"];
- // 将金额转换为字符串并去掉多余的零
- let str = amount.toString().replace(/[^0-9.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./, '').replace('$#$', '.');
- let [integerPart, decimalPart] = str.split('.');
- // 处理整数部分
- let integerLen = integerPart.length;
- let integerResult = '';
- let zeroCount = 0; // 记录连续的零
- for (let i = 0; i < integerLen; i++) {
- let num = integerPart.charAt(i);
- let unitPos = integerLen - i - 1;
- let unitIndex = unitPos % 4;
- // 当前位为零时不进行处理
- if (num === '0') {
- zeroCount++;
- } else {
- if (zeroCount > 0) {
- integerResult += CN_NUMS[0];
- }
- zeroCount = 0;
- integerResult += CN_NUMS[parseInt(num)] + CN_INT[unitIndex];
- }
- if (unitIndex === 0) {
- integerResult += CN_UNIT[Math.floor(unitPos / 4)];
- }
- }
- // 处理小数部分
- let decimalResult = '';
- if (decimalPart) {
- let decimalLen = decimalPart.length;
- for (let i = 0; i < decimalLen; i++) {
- let num = decimalPart.charAt(i);
- if (num !== '0') {
- decimalResult += CN_NUMS[parseInt(num)] + CN_DECIMAL[i];
- }
- }
- }
- if (!decimalResult) {
- decimalResult = '整';
- }
- return integerResult + decimalResult;
- }
|