js 數字金額轉中文大寫格式
moneyToChinese調用示例:
moneyToChinese('199.99');
//console:壹佰玖拾玖元玖角玖分
function moneyToChinese(money) {
let cnNums = new Array('零', '壹', '貳', '叁', '肆', '伍', '陸', '柒', '捌', '玖'); //漢字的數字
let cnIntRadice = new Array('', '拾', '佰', '仟'); //基本機關
let cnIntUnits = new Array('', '萬', '億', '兆'); //對應整數部分擴充機關
let cnDecUnits = new Array('角', '分', '毫', '厘'); //對應小數部分機關
let cnInteger = '整'; //整數金額時後面跟的字元
let cnIntLast = '元'; //整型完以後的機關
let maxNum = 999999999999999.9999; //最大處理的數字
let IntegerNum; //金額整數部分
let DecimalNum; //金額小數部分
let ChineseStr = ''; //輸出的中文金額字元串
let parts; //分離金額後用的數組,預定義
let Symbol = ''; //正負值标記
if(money == '') {
ChineseStr = cnNums[0] + cnIntLast + cnInteger;
return ChineseStr;
}
money = parseFloat(money);
if(money >= maxNum) {
alert('超出最大處理數字');
return '';
}
if(money == 0) {
ChineseStr = cnNums[0] + cnIntLast + cnInteger;
return ChineseStr;
}
if(money < 0) {
money = -money;
Symbol = '負 ';
}
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) { //擷取整型部分轉換
let zeroCount = 0;
let IntLen = IntegerNum.length;
for(let i = 0; i < IntLen; i++) {
let n = IntegerNum.substr(i, 1);
let p = IntLen - i - 1;
let q = p / 4;
let 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 != '') { //小數部分
let decLen = DecimalNum.length;
for(let i = 0; i < decLen; i++) {
let n = DecimalNum.substr(i, 1);
if(n != '0') {
ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
}
}
}
if(ChineseStr == '') {
ChineseStr += cnNums[0] + cnIntLast + cnInteger;
}
else if(DecimalNum == '') {
ChineseStr += cnInteger;
}
ChineseStr = Symbol + ChineseStr;
return ChineseStr;
}