javascript 人民幣小寫轉換為大寫形式程式碼例項

admin發表於2017-03-28

如果在現實生活中寫個欠條或者類似的東西,一般不會用小寫書寫金額,而是使用漢字的大寫形式。

這是因為大寫的金額不容易被篡改,可以說幾乎沒有可能被篡改。

下面就通過程式碼例項介紹一下如何如何利用javascript實現的金額的小寫形式轉換為大寫。

程式碼例項:

[JavaScript] 純文字檢視 複製程式碼
function changeNumMoneyToChinese(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 + cnInteger;
    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 index = 0; index < IntLen; index++) {
      var n = IntegerNum.substr(index, 1);
      var p = IntLen - index - 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 (var index = 0; index < decLen; index++) {
      var n = DecimalNum.substr(index, 1);
      if (n != '0') {
        ChineseStr += cnNums[Number(n)] + cnDecUnits[index];
      }
    }
  }
  if (ChineseStr == '') {
    ChineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (DecimalNum == '') {
    ChineseStr += cnInteger;
  }
  return ChineseStr;
}
console.log(changeNumMoneyToChinese(125.6));

相關文章