JS 写出一个函数,将数字转换成汉语的输出

120 阅读1分钟

偶然看到这个js面试题 觉得很有意思 尝试使用流水账的方式写下来


  • 思路

    将数字按照四位分成几等份, 使用相同的方法翻译每一等份,然后加上单位, 比如

    let num = 12_5678_9876
    

    分成3份,1256789876 工具函数分别翻译并加上单位 十二 亿 五千六百七十八 万 九千八百七十六


直接上代码

const trans = (num)=>{
    const map = {
        0:'零',
        1: '一',
        2: '二',
        3: '三',
        4: '四',
        5: '五',
        6: '六',
        7: '七',
        8: '八',
        9: '九',
    }
    const len = num.toString().length
    x = Math.floor(len/4)
    y = len%4
    const unit = ['十','百','千']
    const a = (x)=>{   // 工具函数 将每一份四位数翻译成汉字
        result = ''
        for(let i=3;i>=0;i--){
            if(i===0 && x!==0){result =  result+map[x]; break} // 碰到个位数 直接返回汉字
            else if(i===0) {result =  result;break} //碰到个位数为0 不管
           if(x%10**i === 0){return (result + map[x/10**i]+unit[i-1]) } //能够整除 直接返回结果
            const xx = Math.floor(x/10**i)==0? '零':map[Math.floor(x/10**i)]+unit[i-1]
            x = x%10**i
            result += xx
        }
    return result.replace('零零', '零') //中间多个0归一
    }
    if(x == 1 && y===0){
        if(a(num)[0]!=='零'){return a(num)}
        const pattern = /[^'零']/
        index = a(num).search(pattern)
        return a(num).slice(index)
        }
    Result = []
    tmpNum = num 
    let j = y===0? x: x+1 
    for(let i=0;i< j;i++){
        if(tmpNum > 10000){
            tmp = tmpNum%10**4
            tmpNum = Math.floor(tmpNum/10**4)}else{
                tmp = tmpNum
            }
        if(i===0){Result.unshift(a(tmp))}
        if(i===1){ Result.unshift( a(tmp)+'万') }
        if(i===2 && y===0){ Result.unshift( a(tmp)+'亿') }
        else if(i===2 && y!==0){ Result= ['一万亿'] }
    }
    return Result.join('').replace(/^零+|零+$/g,'') //去掉首尾的0
}