moneyTransition.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /**
  2. * 数字转为正整数
  3. * @param {*} num
  4. * @returns
  5. */
  6. export function convertPositive(num){
  7. if(num<0){
  8. num=num*-1;
  9. }
  10. return num;
  11. }
  12. /**
  13. * 数字钱转大写(最多可转小数点后两位小数)
  14. * @param {*} amount
  15. */
  16. export function toChies (amount) {
  17. // 汉字的数字
  18. const cnNums = [
  19. "零",
  20. "壹",
  21. "贰",
  22. "叁",
  23. "肆",
  24. "伍",
  25. "陆",
  26. "柒",
  27. "捌",
  28. "玖",
  29. ];
  30. // 基本单位
  31. const cnIntRadice = ["", "拾", "佰", "仟"];
  32. // 对应整数部分扩展单位
  33. const cnIntUnits = ["", "万", "亿", "兆"];
  34. // 对应小数部分单位
  35. const cnDecUnits = ["角", "分"];
  36. // 整数金额时后面跟的字符
  37. const cnInteger = "整";
  38. // 整型完以后的单位
  39. const cnIntLast = "元";
  40. // 最大处理的数字
  41. const maxNum = 9999999999999999.99;
  42. // 金额整数部分
  43. let integerNum;
  44. // 金额小数部分
  45. let decimalNum;
  46. // 输出的中文金额字符串
  47. let chineseStr = "";
  48. // 分离金额后用的数组,预定义
  49. let parts;
  50. if (amount === "") {
  51. return "";
  52. }
  53. amount = parseFloat(amount);
  54. if (amount >= maxNum) {
  55. // 超出最大处理数字
  56. return "";
  57. }
  58. if (amount === 0) {
  59. chineseStr = cnNums[0] + cnIntLast + cnInteger;
  60. return chineseStr;
  61. }
  62. // 转换为字符串
  63. amount = amount.toString();
  64. if (amount.indexOf(".") === -1) {
  65. integerNum = amount;
  66. decimalNum = "";
  67. } else {
  68. parts = amount.split(".");
  69. integerNum = parts[0];
  70. decimalNum = parts[1].substr(0, 4);
  71. }
  72. // 获取整型部分转换
  73. if (parseInt(integerNum, 10) > 0) {
  74. let zeroCount = 0;
  75. const IntLen = integerNum.length;
  76. for (let i = 0; i < IntLen; i++) {
  77. const n = integerNum.substr(i, 1);
  78. const p = IntLen - i - 1;
  79. const q = p / 4;
  80. const m = p % 4;
  81. if (n === "0") {
  82. zeroCount++;
  83. } else {
  84. if (zeroCount > 0) {
  85. chineseStr += cnNums[0];
  86. }
  87. // 归零
  88. zeroCount = 0;
  89. //alert(cnNums[parseInt(n)])
  90. chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
  91. }
  92. if (m === 0 && zeroCount < 4) {
  93. chineseStr += cnIntUnits[q];
  94. }
  95. }
  96. chineseStr += cnIntLast;
  97. }
  98. // 小数部分
  99. if (decimalNum !== "") {
  100. const decLen = decimalNum.length;
  101. for (let i = 0; i < decLen; i++) {
  102. const n = decimalNum.substr(i, 1);
  103. if (n !== "0") {
  104. chineseStr += cnNums[Number(n)] + cnDecUnits[i];
  105. }
  106. }
  107. }
  108. if (chineseStr === "") {
  109. chineseStr += cnNums[0] + cnIntLast + cnInteger;
  110. } else if (decimalNum === "") {
  111. chineseStr += cnInteger;
  112. }
  113. return chineseStr;
  114. }