文章目录
function numberToChinese(num) {
const chineseNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
const chineseUnits = ['', '十', '百', '千', '万', '十万', '百万', '千万', '亿'];
if (num === 0) {
return chineseNums[0];
}
let chineseStr = '';
let unitIndex = 0;
while (num > 0) {
if (unitIndex > 8) {
const start = chineseNums.indexOf(chineseStr[0]);
const end = chineseStr.slice(1, -1);
chineseStr = `${num}${start}${end}`;
break;
}
const remainder = num % 10;
if (remainder) {
if (unitIndex === 1 && num < 10) {
chineseStr = chineseUnits[unitIndex] + chineseStr;
} else {
console.log(chineseNums[remainder], chineseUnits[unitIndex], chineseStr);
if (chineseStr.includes('万')) {
chineseStr = chineseNums[remainder] + chineseUnits[unitIndex].replace('万', '') + chineseStr;
} else {
chineseStr = chineseNums[remainder] + chineseUnits[unitIndex] + chineseStr;
}
}
} else {
chineseStr = chineseNums[remainder] + chineseStr;
}
if (chineseStr.charAt(chineseStr.length - 1) === chineseNums[0]) {
chineseStr = chineseStr.slice(0, -2);
}
chineseStr = chineseStr.replace('零零', '零');
num = Math.floor(num / 10);
unitIndex += 1;
}
return chineseStr;
}
console.log(numberToChinese(0));
console.log(numberToChinese(9));
console.log(numberToChinese(11));
console.log(numberToChinese(498827030));
console.log(numberToChinese(220830734));
console.log(numberToChinese(33320001111));