Skip to content

Instantly share code, notes, and snippets.

@iahu
Created September 26, 2014 02:56
Show Gist options
  • Save iahu/3b131154831740dd92a4 to your computer and use it in GitHub Desktop.
Save iahu/3b131154831740dd92a4 to your computer and use it in GitHub Desktop.
阿拉伯数字转中文数字
function toChineseNumeral(num){
var numerals = {
'-':'负',
'.':'点',
0:'零',
1:'一',
2:'二',
3:'三',
4:'四',
5:'五',
6:'六',
7:'七',
8:'八',
9:'九',
10:'十',
100:'百',
1000:'千',
10000:'万'
};
num = ''+num;
var n = '';
var tmp = num.split('.');
var intNum = tmp[0];
var floatNum = tmp[1];
var intNumLen = intNum.length;
var sign = '';
var intStr='',floatStr= '';
var padding = '000000000000000';
if (intNum.indexOf('-') === 0) {
intNum = intNum.slice(1);
sign = numerals['-'];
intNumLen -= 1;
}
for (var i = 0; i < intNumLen; i++) {
n = intNum[i];
if (i > 0 && intNumLen > 1 && intNum[i-1] > 0) {
intStr += numerals['1'+ padding.slice(intNumLen-i)];
}
intStr += numerals[ n ];
}
intStr = intStr
.replace(/^一十/, '十')
.replace(/^(.+?)零{1,}(.+)$/, '$1零$2')
.replace( /(.+?)零{1,}$/, '$1');
if (floatNum) {
floatStr += numerals['.'];
for(var j=0; j<floatNum.length; j++) {
n = floatNum[j];
floatStr += numerals[ n ];
}
}
return sign+intStr+floatStr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment