59 lines
1.7 KiB
JavaScript
59 lines
1.7 KiB
JavaScript
|
|
// currencyFormatter.js
|
||
|
|
|
||
|
|
export function numberToCNY(amount) {
|
||
|
|
if (amount === 0) return '零元整';
|
||
|
|
const CN_NUMS = ['', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
|
||
|
|
const CN_INT_UNITS = ['', '拾', '佰', '仟'];
|
||
|
|
const CN_INT_BASE = ['元', '萬', '億', '兆'];
|
||
|
|
const CN_DEC_UNITS = ['角', '分'];
|
||
|
|
const INT_MAX = Math.pow(10, 16) - 1;
|
||
|
|
|
||
|
|
if (amount >= INT_MAX || amount <= -INT_MAX) {
|
||
|
|
throw new Error('超出支持的金额范围');
|
||
|
|
}
|
||
|
|
|
||
|
|
let parts = amount.toString().split('.');
|
||
|
|
let integerPart = parts[0];
|
||
|
|
let decimalPart = parts[1] || '';
|
||
|
|
|
||
|
|
// 处理整数部分
|
||
|
|
function convertInteger(numStr) {
|
||
|
|
let result = '';
|
||
|
|
let zeros = 0;
|
||
|
|
let unitPos = 0;
|
||
|
|
for (let i = numStr.length - 1; i >= 0; i--) {
|
||
|
|
let num = parseInt(numStr.charAt(i));
|
||
|
|
if (num === 0) {
|
||
|
|
zeros++;
|
||
|
|
} else {
|
||
|
|
if (zeros > 0) {
|
||
|
|
result = '零' + result;
|
||
|
|
}
|
||
|
|
zeros = 0;
|
||
|
|
result = CN_NUMS[num] + CN_INT_UNITS[unitPos % 4] + result;
|
||
|
|
}
|
||
|
|
unitPos++;
|
||
|
|
if (unitPos % 4 === 0 && i > 0) {
|
||
|
|
result = CN_INT_BASE[Math.floor(unitPos / 4) - 1] + result;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return result.trim();
|
||
|
|
}
|
||
|
|
|
||
|
|
// 处理小数部分
|
||
|
|
function convertDecimal(numStr) {
|
||
|
|
return numStr.split('').map((digit, index) => {
|
||
|
|
return digit !== '0' ? CN_NUMS[digit] + CN_DEC_UNITS[index] : '';
|
||
|
|
}).join('');
|
||
|
|
}
|
||
|
|
|
||
|
|
let integerResult = convertInteger(integerPart);
|
||
|
|
let decimalResult = decimalPart.length > 0 ? convertDecimal(decimalPart) : '整';
|
||
|
|
|
||
|
|
// 连接整数和小数部分,并确保格式正确
|
||
|
|
let finalResult = integerResult.replace(/零+$/, '') + '元' + decimalResult;
|
||
|
|
finalResult = finalResult.replace(/零+/g, '零');
|
||
|
|
|
||
|
|
return finalResult;
|
||
|
|
}
|