JavaScript 把阿拉伯数字转为财务数字
🌙
手机阅读
本文目录结构
替换文字
- 先把大正则匹配的内容捕获到(捕获到的结果个我们用 exec 捕获到的结果基本一致)
- 把我们捕获的内容进行替换
var str = "20151215";
var reg = /\d/g;
var ary = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
// 一共要捕获 8 次,我们的第二个参数 [function] 要执行 8 次
// 每一执行都把当前正则捕获的内容传递给我们的 [function]
// 每一次执行的返回值(写在 return 后面的)都相当于把当前大正则捕获的内容替换成我们返回的内容
str = str.replace(reg, function () {
// 第一次捕获 2 ->"贰" ary[2]
// 第二次捕获 0 ->"零" ary[0]
//arguments[0]->每一次执行函数我们正则捕获到的内容
console.log(arguments);
// 第一次:arguments->["2", 0, "20151215"] arguments[0]->"2"
return ary[arguments[0]];//->return ary["2"] ->return "贰";
});
console.log(str);// 贰零壹伍壹贰壹伍
阿拉伯数字转为财务数字
function toChinaNumber (options) {
options=options+"";
options = options.replace(/^0+/, "");
var numberAry = ["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"],
unitAry = ["","拾","佰","仟"],
bigUnitAry = ["","万","亿"];
var targetStr = "";
var zeroFlag = 0;
var i, p, nowAloneNumber;
var quotient, modulus;
var len=options.length;
if(len==0){
targetStr += "零";
}else{
for (i = 0; i < len; i++) {
p = len - i - 1;
nowAloneNumber = options.substr(i, 1);
quotient = p / 4;// 商
modulus = p % 4;// 余数
if (nowAloneNumber == "0") {
zeroFlag++;
} else {
if (zeroFlag > 0) {
targetStr += numberAry[0];
}
zeroFlag = 0;
targetStr += numberAry[Number(nowAloneNumber)] + unitAry[modulus];
}
if (modulus == 0 && zeroFlag < 4) {
targetStr += bigUnitAry[quotient];
zeroFlag = 0;
}
}
}
targetStr += "元整";
return targetStr;
}
var testNumber=35987;
var testStr="298";
console.log(toChinaNumber(testNumber));
console.log(toChinaNumber(testStr));