输入数字输出中文(1>一,10>十,21>二十一)
const numberToChinese = num => {
if (Number.isNaN(num)) return '不是数字'
if (num < 0) return '不支持负数'
if (num < 10) return '零一二三四五六七八九十'[num]
const units = ['', '十', '百', '千']
const bigUnits = ['万', '亿', '兆']
let str = ''
let n = num
let unitIndex = 0
function getChinese(m, index) {
let tempStr = ''
let i = 0
while (i < 4 && m > 0) {
const digit = m % 10
m = Math.floor(m / 10)
if (digit !== 0) {
tempStr = '零一二三四五六七八九十'[digit] + units[i] + tempStr
} else if (i === 1 && m > 0) { // 处理十位数字为0的情况,但只有当百位数字不为0时
tempStr = '十' + tempStr
} else if (i > 0 && tempStr !== '') { // 在百位和千位之前添加“零”
tempStr = '零' + tempStr
}
i++
}
if (index > 0 && tempStr !== '') {
tempStr += bigUnits[index - 1]
}
return tempStr
}
while (n !== 0) {
const part = n % 10000
str = getChinese(part, unitIndex) + str
n = Math.floor(n / 10000)
unitIndex++
}
return str.replace(/零(千|百|十)/g, '零').replace(/零+/g, '零').replace(/零(万|亿|兆)/g, '$1').replace(/一十/g, '十').replace(/零+$/, '')
}