本帖最后由 二麻子 于 2024-10-28 17:10 编辑
- 最后两行代码是适配活字格的,money和outPut分别指代单元格名称,money输入数字,output输入中文
复制代码- //数字转大写
- function convertToChineseCurrency(num) {
- // 确保 num 是数字
- num = Number(num);
- // 定义数字对应的大写中文
- const digits = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
- const units = ["", "拾", "佰", "仟"];
- const bigUnits = ["", "万", "亿"];
- const decimalUnits = ["角", "分"];
- // 强制保留两位小数,并拆分整数和小数部分
- const [integerPart, decimalPart] = num.toFixed(2).split(".");
- // 转换整数部分
- let integerResult = "";
- const integerArray = integerPart.split("").reverse();
- for (let i = 0; i < integerArray.length; i++) {
- const digit = parseInt(integerArray[i]);
- const unit = units[i % 4];
- const bigUnit = bigUnits[Math.floor(i / 4)];
- if (digit === 0) {
- if (!integerResult.startsWith("零") && integerResult) {
- integerResult = "零" + integerResult;
- }
- } else {
- integerResult = digits[digit] + unit + bigUnit + integerResult;
- }
- }
- integerResult = integerResult.replace(/零+/g, "零").replace(/零$/, "");
- // 转换小数部分
- let decimalResult = "";
- if (decimalPart !== "00") {
- const jiao = parseInt(decimalPart.charAt(0));
- const fen = parseInt(decimalPart.charAt(1));
- if (jiao > 0) decimalResult += digits[jiao] + decimalUnits[0];
- if (fen > 0) decimalResult += digits[fen] + decimalUnits[1];
- }
- // 合并整数和小数部分
- return integerResult + "元" + (decimalResult || "整");
- }
- value = convertToChineseCurrency(Forguncy.Page.getCell("money").getValue())
- Forguncy.Page.getCell("outPut").setValue(value)
复制代码- // 中文大写金额转数字
- function convertChineseCurrencyToNumber(chineseCurrency) {
- // 定义大写数字对应的数值
- const chineseDigits = {
- "零": 0, "壹": 1, "贰": 2, "叁": 3, "肆": 4,
- "伍": 5, "陆": 6, "柒": 7, "捌": 8, "玖": 9
- };
- const units = { "拾": 10, "佰": 100, "仟": 1000 };
- const bigUnits = { "万": 10000, "亿": 100000000 };
- const decimalUnits = { "角": 0.1, "分": 0.01 };
- let integerPart = 0;
- let decimalPart = 0;
- let tempNum = 0;
- let unit = 1;
- for (let i = 0; i < chineseCurrency.length; i++) {
- const char = chineseCurrency[i];
- if (chineseDigits[char] !== undefined) {
- tempNum = chineseDigits[char];
- } else if (units[char] !== undefined) {
- unit = units[char];
- integerPart += tempNum * unit;
- tempNum = 0;
- unit = 1;
- } else if (bigUnits[char] !== undefined) {
- integerPart = (integerPart + tempNum) * bigUnits[char];
- tempNum = 0;
- } else if (decimalUnits[char] !== undefined) {
- decimalPart += tempNum * decimalUnits[char];
- tempNum = 0;
- } else if (char === "元") {
- integerPart += tempNum;
- tempNum = 0;
- } else if (char === "整") {
- break;
- }
- }
- integerPart += tempNum;
- return integerPart + decimalPart;
- }
- value = convertChineseCurrencyToNumber(Forguncy.Page.getCell("outPut").getValue());
- Forguncy.Page.getCell("money").setValue(value);
复制代码
|