Skip to content

Instantly share code, notes, and snippets.

@caorong
Created July 7, 2014 14:24
Show Gist options
  • Save caorong/97c1866fca1d5237acb5 to your computer and use it in GitHub Desktop.
Save caorong/97c1866fca1d5237acb5 to your computer and use it in GitHub Desktop.
sm's interview question
function numberToCN(number){
number = parseInt(number,0);
if(isNaN(number)){
return false;
}
if(number === 0){
return '零';
}
var numberList = (''+number).split(''),
numbeMap = [false,'一','二','三','四','五','六','七','八','九'],
decMap = ['','十','百','千','万','十','百','千','亿','十','百','千','万','兆'];
return numberList.reverse().map(function (val,index){
var vi = parseInt(val,0);
if(vi == 0){
if(index===4 || index === 8 || index === 13){
return decMap[index];
}
return '';
} else {
if(vi == 1 && decMap[index] == '十'){
return '十'
}
return numbeMap[vi]+decMap[index];
}
}).reverse().reduce(function (a,b,index) {
// console.log(arguments);
var tmp = a+b;
if(!b){
if(numberList.length-index<=2){
if(tmp.substr(tmp.length-1,1) !== '零'){
tmp += '零';
}
}
}
if(index == numberList.length-1){
if(tmp.substr(tmp.length-1,1) == '零'){
return tmp.substr(0,tmp.length-1)
}
}
return tmp;
});
}
// test
numberToCN(1234563124) // => 一十二亿三千四百五十六万三千一百二十四
numberToCN(5234) // => 五千二百三十四
numberToCN(12)
numberToCN(102)
numberToCN(10000)
numberToCN(130202)
numberToCN(10002)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment