轉載自:https://www.zuojl.com/convert-menoy-chinese-use-js/
敘述
在工作中經常會遇到需要將金額轉換成繁體數組進行展示的情況,這個轉換的過程可以後臺進行也可以在前端進行。
本文使用 JavaScript 將金額數字轉換成中文繁體,廢話不多說直接上代碼:
解決方案
/**
* 將給定的金額數值轉換爲中文繁體的方法,
* 最大值爲'兆'的的數值,不爲負數
* @author zuojl
* @version 2016.05.04 v1.0
* @param money 傳入的金額數值
* @return result 當返回的不是'ERROR'時,
* 返回的是轉換後的金額中文值
*/
var _moneyToChinese = function(money){
//判斷是否爲數字,不是返回'ERROR'
var pattern = /^\d+(.\d{1,2})?$/;
//匹配0,小數,負數:/^(0|-?[1-9][0-9]*)(.[0-9]{1,2})?$/
//匹配100,100的格式:/^(0|((-?[1-9][0-9]{1,2})(,[0-9]{3})*|(0|-?[1-9][0-9]*))(.[0-9]{1,2})?)$/
if(money == '' || !pattern.test(money)){
return 'ERROR!';
}
money += '';
var s1 = new Array('零', '壹', '貳', '叄', '肆', '伍', '陸', '柒', '捌', '玖');//存儲數值部分
var s2 = new Array('分', '角', '圓', '拾', '佰', '仟', '萬', '拾', '佰', '仟', '億', '拾', '佰', '仟', '萬', '億', '兆');//存儲單位部分
//將money字符串轉化爲分
var str;//用來存儲轉化爲分的字符串
var result = '';//用來存儲
var index = money.lastIndexOf(".");
if(index != -1){
var temp = money.substring(index + 1);
var len = temp.length;
if(len > 2){
len = 2;
temp = temp.substring(0, 2);
}
for(var i = 0; i < 2 - len; i++){
temp += '0';
}
str = money.substring(0, index) + temp;
} else {
str = money + '00';
}
/*
* 將分的每一位數字取出
* 將其與數值和單位部分進行匹配
* 組合成轉換後的金額
*/
for (i = 0; i < str.length; i++) {
var n = str.charAt(str.length - 1 - i);
result = s1[n] + "" + s2[i] + result;
}
/*
* 通過正則優化
*/
//優化有零的
result = result.replace(/零分/g, "零");
result = result.replace(/零角/g, "零");
result = result.replace(/零圓/g, "零");
result = result.replace(/零拾/g, "零");
result = result.replace(/零佰/g, "零");
result = result.replace(/零仟/g, "零");
result = result.replace(/零萬/g, "零");
result = result.replace(/零億/g, "零");
//優化多個相連的零
result = result.replace(/零零/g, "零");
//優化以零結尾的
result = result.replace(/零$/, "");
//優化整元
result = result.replace(/圓$/, "圓整");
result = result.replace(/零圓$/, "零圓整");
return result;
};
實現的代碼也是非常的簡單,將數字數組中的每個字符替換成漢族後,使用正則替換的方式進行優化。