数字金额转换成汉字(100=>零佰)

 

 1 export function convertCurrency(money) {
 2   //汉字的数字
 3   let cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
 4   //基本单位
 5   let cnIntRadice = new Array('', '拾', '佰', '仟');
 6   //对应整数部分扩展单位
 7   let cnIntUnits = new Array('', '万', '亿', '兆');
 8   //对应小数部分单位
 9   let cnDecUnits = new Array('角', '分', '毫', '厘');
10   //整数金额时后面跟的字符
11   let cnInteger = '整';
12   //整型完以后的单位
13   let cnIntLast = '元';
14   //最大处理的数字
15   let maxNum = 999999999999999.9999;
16   //金额整数部分
17   let integerNum;
18   //金额小数部分
19   let decimalNum;
20   //输出的中文金额字符串
21   let chineseStr = '';
22   //分离金额后用的数组,预定义
23   let parts;
24 
25   if (money == '') {
26     return '';
27   }
28   money = parseFloat(money);
29   if (money >= maxNum) {
30     //超出最大处理数字
31     return '';
32   }
33   if (money == 0) {
34     chineseStr = cnNums[0] + cnIntLast + cnInteger;
35     return chineseStr;
36   }
37   //转换为字符串
38   money = money.toString();
39   if (money.indexOf('.') == -1) {
40     integerNum = money;
41     decimalNum = '';
42   } else {
43     parts = money.split('.');
44     integerNum = parts[0];
45     decimalNum = parts[1].substr(0, 4);
46   }
47   //获取整型部分转换
48   if (parseInt(integerNum, 10) > 0) {
49     var zeroCount = 0;
50     var IntLen = integerNum.length;
51     for (var i = 0; i < IntLen; i++) {
52       var n = integerNum.substr(i, 1);
53       var p = IntLen - i - 1;
54       var q = p / 4;
55       var m = p % 4;
56       if (n == '0') {
57         zeroCount++;
58       } else {
59         if (zeroCount > 0) {
60           chineseStr += cnNums[0];
61         }
62         //归零
63         zeroCount = 0;
64         chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
65       }
66       if (m == 0 && zeroCount < 4) {
67         chineseStr += cnIntUnits[q];
68       }
69     }
70     chineseStr += cnIntLast;
71   }
72   //小数部分
73   if (decimalNum != '') {
74     var decLen = decimalNum.length;
75     for (var i = 0; i < decLen; i++) {
76       var n = decimalNum.substr(i, 1);
77       if (n != '0') {
78         chineseStr += cnNums[Number(n)] + cnDecUnits[i];
79       }
80     }
81   }
82   if (chineseStr == '') {
83     chineseStr += cnNums[0] + cnIntLast + cnInteger;
84   } else if (decimalNum == '') {
85     chineseStr += cnInteger;
86   }
87   return chineseStr;
88 }

 

posted @ 2021-01-12 14:38  思猿客  阅读(413)  评论(1编辑  收藏  举报