题解 | #阿拉伯数字转中文#
阿拉伯数字转中文
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
};