// const number = 123456789012345.67
const number = 123456789012345.10
const chineseNumberMapping = {
'0': '零',
'1': '壹',
'2': '贰',
'3': '叁',
'4': '肆',
'5': '伍',
'6': '陆',
'7': '柒',
'8': '捌',
'9': '玖',
}
const chineseNumberDigitMapping = {
3: '',
2: '拾',
1: '佰',
0: '仟'
}
const chineseNumberDecimalMapping = {
0: '角',
1: '分'
}
function convertNumberToChinese (num) {
const MAX_VALUE = 999999999999999.99
if (Number(num) > MAX_VALUE) {
return false
} else {
let strNum = String(num)
let [strInteger, strDecimal] = strNum.split('.')
let arrStrNum = []
for (let i = 0; i < strInteger.length; i++) {
arrStrNum.push(strInteger.charAt(i))
}
let chineseInteger = convertInteger(strInteger)
let chineseDecimal = ''
if (strDecimal) {
chineseDecimal = convertDecimal(strDecimal)
}
let result = ''
if (chineseDecimal) {
result = chineseInteger + '元' +chineseDecimal
} else {
result = chineseInteger + '元整'
}
console.log(strInteger, strDecimal, chineseInteger, chineseDecimal)
return result
}
}
function convertInteger (strInteger) {
let loopTimes = Math.trunc(strInteger.length / 4);
let levels = []
let tempInteger = strInteger
if (strInteger.length % 4 > 0) loopTimes += 1
for (let i = 0; i < loopTimes; i++) {
let levelNum = strInteger.substring(strInteger.length - (4 * (i + 1)), strInteger.length - (4 * i))
let chineseLevelNum = convertIntegerLevel(levelNum)
if (i === 1 || i === 3) {
chineseLevelNum += '萬'
}
if (i === 2) {
chineseLevelNum += '亿'
}
levels.unshift(chineseLevelNum)
}
return levels.join('').replace(/(零*)([零壹贰叁肆伍陆柒捌玖拾佰仟]+[壹贰叁肆伍陆柒捌玖拾佰仟])(零*)/, '$2')
}
function convertIntegerLevel (strLevelInteger) {
if (strLevelInteger.length > 0 && strLevelInteger.length < 5) {
let result = ''
strLevelInteger = strLevelInteger.padStart(4, '0')
for (let i = strLevelInteger.length - 1; i > -1; i--) {
let num = strLevelInteger.charAt(i)
if (num === '0') {
result = chineseNumberMapping[num] + result
} else {
result = chineseNumberMapping[num] + chineseNumberDigitMapping[i] + result
}
}
return result.replace(/(零?)(零*)([零壹贰叁肆伍陆柒捌玖拾佰仟]+[壹贰叁肆伍陆柒捌玖拾佰仟])(零*)/, '$1$3').replace('零零', '零')
} else {
return false
}
}
function convertDecimal (strDecimal) {
if (strDecimal && strDecimal.length > 0 && strDecimal.length < 3) {
let result = ''
for (let i = 0 ; i < strDecimal.length; i++) {
let num = strDecimal.charAt(i)
if (num === '0') {
result = result + chineseNumberMapping[num]
} else {
result = result + chineseNumberMapping[num] + chineseNumberDecimalMapping[i]
}
}
if (result === '零零') {
return ''
} else if (result.endsWith('零')) {
return result.replace('零', '整')
} else {
return result
}
} else {
return false
}
}
console.log(convertNumberToChinese(number))
console