把阿拉伯数字1,21,301…转化成一,二十一,三百零一;最大到千亿,可扩展
很多时候后端提供的sortIndex是number
类型,当有需求:大标题一、二等等,或者需要转换成中文数字。
纯原创,工作闲暇写的,记个笔记,欢迎指教不足之处,不断优化。
const parseNumberToChineseCharacter = num => {
let number = String(num)
// 单位 可加'个',只需在 //****处-2改为-1
let unit = '十百千万十百千亿十百千'
// 中文枚举的字符串
let enumStr = '零一二三四五六七八九'
// 存放结果
let newStr = ''
if (number.length > unit.length) {
return '数字过长'
}
for (let n = 0; n < number.length; n++) {
// 处理0,不是0则拼接单位
if (enumStr.charAt(number[n]) === '零') {
// 当前位是万、亿
let currentUnit = unit[number.length - n - 2]
if ( currentUnit === '万' || currentUnit === '亿') {
newStr += currentUnit
}
// 前一位连着是0,则不继续拼接
if (newStr[newStr.length - 1] !== '零') {
newStr += '零'
}
} else {
newStr += enumStr.charAt(number[n]) + unit.charAt(number.length - n - 2)// ****
}
}
// 习惯将开头的 一十 读作 十
if (newStr.slice(0, 2) === '一十') {
newStr = newStr.slice(1)
}
// 处理末尾的 零
if (newStr[newStr.length - 1] === '零') {
newStr = newStr.slice(0, newStr.length - 1)
}
// 处理 零万、零亿
newStr = newStr.replace(/零万/, '万')
newStr = newStr.replace(/零亿/, '亿')
return newStr
}
// 1100101 => 一百一十万零一百零一
// 11100101 => 一千一百一十万零一百零一
// 1011100101 => 十亿零一千一百一十万零一百零一
// 10011100101=> 一百亿零一千一百一十万零一百零一