题解 | #阿拉伯数字转中文#

阿拉伯数字转中文

http://www.nowcoder.com/practice/6eec992558164276a51d86d71678b300

万和亿单独判断

function num2cn( n ) {
    let flag = false
    if(n<0) flag = true
    n = Math.abs(n).toString()
    const table = {
        1: '一',
        2: '二',
        3: '三',
        4: '四',
        5: '五',
        6: '六',
        7: '七',
        8: '八',
        9: '九',
        0: '零',
    }
    if(n.length == 1) return table[n]
    const unit = ['', '十', '百', '千']
    let str = '', len = n.length, mark
        
    for(let i = 0; i < n.length; i++,len--) {
        if(len/4 === 1) str += str[str.length-1] === '亿' ? '' : '万'
        if(len/4 === 2) str += '亿'
        if(n[i] != 0) {
            if(n[i-1] == 0) str += '零'
            mark = unit[(len-1) % 4]
            str += table[n[i]] + mark
        }
    }
    if(n.length%4 === 2 && n[0] === '1') str = str.substring(1)
    return flag ? '负'+str : str
    // write code here
}
module.exports = {
    num2cn : num2cn
};
全部评论

相关推荐

码农索隆:这种hr,建议全中国推广
点赞 评论 收藏
分享
每晚夜里独自颤抖:你cet6就cet6,cet4就cet4,你写个cet证书等是什么意思。专业技能快赶上项目行数,你做的这2个项目哪里能提现你有这么多技能呢
点赞 评论 收藏
分享
下北澤大天使:你是我见过最美的牛客女孩😍
点赞 评论 收藏
分享
榕城小榕树:1200单休,我去干点啥别的不好
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务