Js function that converts a number to a capitalized RMB expression

  • 2020-03-30 03:57:10
  • OfStack

There are many ways to convert the number to uppercase RMB, this example is to use js to complete, look at the following implementation code


function changeNumMoneyToChinese(money) {
  var cnNums = new Array(" zero ", " one ", " Ii. ", " 3 ", " boss ", " wu ", " lu ", " Retailer, ", "  ", " nine "); //Number of Chinese characters
  var cnIntRadice = new Array("", " Pick up ", " hk ", " micky "); //The basic unit
  var cnIntUnits = new Array("", " wan ", " Hundred million ", " mega "); //Extends the unit corresponding to the integer part
  var cnDecUnits = new Array(" Angle ", " points ", " milli ", " li "); //That's the decimal unit
  var cnInteger = " The whole "; //The character followed by an integer amount
  var cnIntLast = " yuan "; //The unit after the completion of the integer
  var maxNum = 999999999999999.9999; //Maximum number processed
  var IntegerNum; //Integral part of amount
  var DecimalNum; //Fractional part of amount
  var ChineseStr = ""; //The output Chinese amount string
  var parts; //Split the amount of the used array, predefined
  if (money == "") {
    return "";
  }
  money = parseFloat(money);
  if (money >= maxNum) {
    alert(' Exceed the maximum processing number ');
    return "";
  }
  if (money == 0) {
    ChineseStr = cnNums[0] + cnIntLast + cnInteger;
    return ChineseStr;
  }
  money = money.toString(); //Convert to string
  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) { //Gets an integer partial transformation
    var zeroCount = 0;
    var IntLen = IntegerNum.length;
    for (var i = 0; i < IntLen; i++) {
      var n = IntegerNum.substr(i, 1);
      var p = IntLen - i - 1;
      var q = p / 4;
      var m = p % 4;
      if (n == "0") {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          ChineseStr += cnNums[0];
        }
        zeroCount = 0; // zero 
        ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        ChineseStr += cnIntUnits[q];
      }
    }
    ChineseStr += cnIntLast;
    //The integral part is finished
  }
  if (DecimalNum != '') { //The decimal part
    var decLen = DecimalNum.length;
    for (var i = 0; i < decLen; i++) {
      var 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;
  }
  return ChineseStr;

}

Related articles: