forked from yanlele/node-index
-
Notifications
You must be signed in to change notification settings - Fork 2
/
rmbHelper.js
100 lines (95 loc) · 3.28 KB
/
rmbHelper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
function convertRmb(money) {
var cnNums = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); //汉字的数字
var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本单位
var cnIntUnits = new Array("", "万", "亿", "兆"); //对应整数部分扩展单位
var cnDecUnits = new Array("角", "分", "毫", "厘"); //对应小数部分单位
var cnInteger = "整"; //整数金额时后面跟的字符
var cnIntLast = "元"; //整型完以后的单位
var maxNum = 999999999999999.9999; //最大处理的数字
var IntegerNum; //金额整数部分
var DecimalNum; //金额小数部分
var ChineseStr = ""; //输出的中文金额字符串
var parts; //分离金额后用的数组,预定义
if (money == "") {
return "";
}
money = parseFloat(money);
if (money >= maxNum) {
$.alert('超出最大处理数字');
return "";
}
if (money == 0) {
ChineseStr = cnNums[0] + cnIntLast
return ChineseStr;
}
money = money.toString(); //转换为字符串
if (money.indexOf(".") == -1) {
IntegerNum = money;
DecimalNum = '';
} else {
parts = money.split(".");
IntegerNum = parts[0];
DecimalNum = parts[1].substr(0, 4);
}
if (parseInt(IntegerNum, 10) > 0) {//获取整型部分转换
var zeroCount = 0;
var IntLen = IntegerNum.length;
for (var i = 0; i < IntLen; i++) {
var n = IntegerNum.substr(i, 1);
var p = IntLen - i - 1;
var q = p / 4;
var m = p % 4;
if (n == "0") {
zeroCount++;
} else {
if (zeroCount > 0) {
ChineseStr += cnNums[0];
}
zeroCount = 0; //归零
ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
}
if (m == 0 && zeroCount < 4) {
ChineseStr += cnIntUnits[q];
}
}
ChineseStr += cnIntLast;
}
if (DecimalNum != '') {//小数部分
var decLen = DecimalNum.length;
for (i = 0; i < decLen; i++) {
n = DecimalNum.substr(i, 1);
if (n != '0') {
ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
}
}
}
if (ChineseStr == '') {
ChineseStr += cnNums[0] + cnIntLast;
}
if(ChineseStr.charAt(ChineseStr.length - 1)==cnIntLast){
ChineseStr+=cnInteger
}
return ChineseStr;
}
function rmbToNum(rmb){
var num="";
rmb=rmb.indexOf('元')==rmb.length-1?rmb+'整':rmb;
rmb=rmb.replace('圆','元');
var cnNums = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); //汉字的数字
for(var i=0;i<rmb.length;i++){
if(cnNums.indexOf(rmb[i])>-1){
num=num+cnNums.indexOf(rmb[i])
}
if(rmb.indexOf('拾元')>-1 && rmb[i]=='元'){
num=num+'0';
}
if(rmb[i]=='元' && rmb.indexOf('整')==-1 && rmb.indexOf('元')!=rmb.length-1 && num.indexOf('.')==-1){//如果不包含整且元后面有值则添加小数点
num=num+'.';
}
}
return num;
}
module.exports = {
convert: convertRmb,
rmbToNum:rmbToNum
};