将数字转汉字处理
在不方便安装第三方库的情况下,需要的可以直接复制使用即可,不支持负数懒得写了
`numberToChineseInteger(num) {
if (num === 0) return '零';
if (num < 0 || !Number.isInteger(num)) return '';
const digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
const units = ['', '十', '百', '千'];
const bigUnits = ['', '万', '亿', '兆', '京', '垓', '秭', '穰', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他',
'不可思议', '无量大数', '古戈尔'
];
let result = '';
let unitPos = 0;
let lastSectionHasValue = false;
while (num > 0) {
const section = num % 10000;
num = Math.floor(num / 10000);
let sectionStr = '';
let temp = section;
let hasValue = false;
let zeroFlag = false;
for (let i = 0; i < 4 && temp > 0; i++) {
const digit = temp % 10;
temp = Math.floor(temp / 10);
if (digit !== 0) {
if (zeroFlag) {
sectionStr = digits[0] + sectionStr;
zeroFlag = false;
}
// 处理"一十"的情况(省略"一")
if (digit === 1 && i === 1 && temp === 0) {
sectionStr = units[i] + sectionStr; // 直接拼接"十",不拼接"一"
} else {
sectionStr = digits[digit] + units[i] + sectionStr;
}
hasValue = true;
} else if (sectionStr.length > 0) {
zeroFlag = true;
}
}
if (hasValue) {
sectionStr += bigUnits[unitPos];
result = sectionStr + result;
lastSectionHasValue = true;
} else if (lastSectionHasValue && num > 0) {
result = digits[0] + result;
lastSectionHasValue = false;
}
unitPos++;
}
return result;
}`