人民币工具类

RmbUtils = {
    convertCurrency: function (currencyDigits) {
        //常量
        var MAXIMUM_NUMBER = 99999999999.99;
        //预先定义输出的基数字符和货币符号:
        var CN_ZERO = "零";
        var CN_ONE = "壹";
        var CN_TWO = "贰";
        var CN_THREE = "叁";
        var CN_FOUR = "肆";
        var CN_FIVE = "伍";
        var CN_SIX = "陆";
        var CN_SEVEN = "柒";
        var CN_EIGHT = "捌";
        var CN_NINE = "玖";
        var CN_TEN = "拾";
        var CN_HUNDRED = "佰";
        var CN_THOUSAND = "仟";
        var CN_TEN_THOUSAND = "万";
        var CN_HUNDRED_MILLION = "亿";
        var CN_SYMBOL = "";
        var CN_DOLLAR = "元";
        var CN_TEN_CENT = "角";
        var CN_CENT = "分";
        var CN_INTEGER = "整";
        // 变量:
        var integral; // Represent integral part of digit number.
        var decimal; // Represent decimal part of digit number.
        var outputCharacters; // The output result.
        var parts;
        var digits, radices, bigRadices, decimals;
        var zeroCount;
        var i, p, d;
        var quotient, modulus;
        // 校验输入字符串:
        currencyDigits = currencyDigits.toString();
        if (currencyDigits == "") {
            alert("不能为空。");
            return false;
        }
        if (currencyDigits.match(/[^,.\d]/) != null) {
            alert("请输入数字。");
            return '';
        }
        if ((currencyDigits).match(/^((\d{1,3}(,\d{3})*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$/) == null) {
            alert("请输入正确数字。");
            return false;
        }
        // 将输入数字的格式标准化
        currencyDigits = currencyDigits.replace(/,/g, ""); // Remove comma delimiters.
        currencyDigits = currencyDigits.replace(/^0+/, ""); // Trim zeros at the beginning.
        // 超出了最大数字转换
        if (Number(currencyDigits) > MAXIMUM_NUMBER) {
            alert("超出了最大数字转换。");
            return false;
        }
        //处理货币数字到字符的转换
        // 将积分部分和小数部分分开
        parts = currencyDigits.split(".");
        if (parts.length > 1) {
            integral = parts[0];
            decimal = parts[1];
            // 小数保留2位.
            decimal = decimal.substr(0, 2);
        } else {
            integral = parts[0];
            decimal = "";
        }
        // 准备数字对应的字符
        digits = new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE);
        radices = new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND);
        bigRadices = new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION);
        decimals = new Array(CN_TEN_CENT, CN_CENT);
        //开始处理
        outputCharacters = "";
        // 处理整数部分
        if (Number(integral) > 0) {
            zeroCount = 0;
            for (i = 0; i < integral.length; i++) {
                p = integral.length - i - 1;
                d = integral.substr(i, 1);
                quotient = p / 4;
                modulus = p % 4;
                if (d == "0") {
                    zeroCount++;
                } else {
                    if (zeroCount > 0) {
                        outputCharacters += digits[0];
                    }
                    zeroCount = 0;
                    outputCharacters += digits[Number(d)] + radices[modulus];
                }
                if (modulus == 0 && zeroCount < 4) {
                    outputCharacters += bigRadices[quotient];
                    zeroCount = 0;
                }
            }
            outputCharacters += CN_DOLLAR;
        }
        // 处理小数部分
        if (decimal != "") {
            for (i = 0; i < decimal.length; i++) {
                d = decimal.substr(i, 1);
                if (d != "0") {
                    outputCharacters += digits[Number(d)] + decimals[i];
                }
            }
        }
        // 确认并返回处理结果
        if (outputCharacters == "") {
            outputCharacters = CN_ZERO + CN_DOLLAR;
        }
        if (decimal == "") {
            outputCharacters += CN_INTEGER;
        }
        outputCharacters = CN_SYMBOL + outputCharacters;
        return outputCharacters;
    }
}
/**
 * 货币工具类
 * 支持人民币等货币的数字与大写转换
 */
class CurrencyUtils {
    /**
     * 货币配置
     */
    static #configs = {
        cny: {
            name: "人民币",
            symbol: "",
            digits: ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"],
            radices: ["", "拾", "佰", "仟"],
            bigRadices: ["", "万", "亿"],
            decimals: ["角", "分"],
            unit: "元",
            integer: "整",
            maximum: 99999999999.99
        }
        // 可添加其他货币配置
    };

    /**
     * 将数字转换为货币大写
     * @param {number|string} amount 金额
     * @param {string} currency 货币类型,默认为人民币(cny)
     * @return {string} 货币大写
     * @throws {Error} 输入错误时抛出异常
     */
    static toChinese(amount, currency = "cny") {
        const config = this.#configs[currency];
        if (!config) {
            throw new Error(`不支持的货币类型: ${currency}`);
        }

        const { 
            maximum, 
            digits, 
            radices, 
            bigRadices, 
            decimals, 
            symbol, 
            unit, 
            integer 
        } = config;

        // 输入验证
        if (amount === undefined || amount === null) {
            throw new Error("金额不能为空");
        }

        const input = String(amount);
        if (/[^,.\d-]/.test(input)) {
            throw new Error("请输入有效的金额");
        }

        // 处理负数
        const isNegative = input.startsWith("-");
        const normalized = input.replace(/^-/, "").replace(/,/g, "").replace(/^0+/, "");
        if (!normalized) {
            return symbol + digits[0] + unit + integer;
        }

        if (Number(normalized) > maximum) {
            throw new Error(`金额超出最大转换范围: ${maximum}`);
        }

        // 分离整数和小数部分
        const parts = normalized.split(".");
        const integral = parts[0] || "0";
        const decimal = parts[1] ? parts[1].substr(0, decimals.length) : "";

        let output = [];

        // 处理整数部分
        if (Number(integral) > 0) {
            let zeroCount = 0;
            for (let i = 0; i < integral.length; i++) {
                const p = integral.length - i - 1;
                const d = integral.substr(i, 1);
                const quotient = Math.floor(p / 4);
                const modulus = p % 4;

                if (d === "0") {
                    zeroCount++;
                } else {
                    if (zeroCount > 0) {
                        output.push(digits[0]);
                    }
                    zeroCount = 0;
                    output.push(digits[Number(d)], radices[modulus]);
                }

                if (modulus === 0 && zeroCount < 4) {
                    output.push(bigRadices[quotient]);
                    zeroCount = 0;
                }
            }
            output.push(unit);
        }

        // 处理小数部分
        if (decimal) {
            for (let i = 0; i < decimal.length; i++) {
                const d = decimal.substr(i, 1);
                if (d !== "0") {
                    output.push(digits[Number(d)], decimals[i]);
                }
            }
        }

        // 处理特殊情况
        if (output.length === 0) {
            output.push(digits[0], unit);
        }
        if (!decimal) {
            output.push(integer);
        }

        let result = symbol + output.join("");
        return isNegative ? `负${result}` : result;
    }

    /**
     * 将人民币大写转换为数字
     * @param {string} chinese 人民币大写
     * @return {number} 数字
     * @throws {Error} 输入错误时抛出异常
     */
    static fromChinese(chinese) {
        if (!chinese || typeof chinese !== "string") {
            throw new Error("输入不能为空");
        }

        // 简化实现,实际项目中需要更复杂的处理
        const digitMap = {
            "零": 0, "壹": 1, "贰": 2, "叁": 3, "肆": 4,
            "伍": 5, "陆": 6, "柒": 7, "捌": 8, "玖": 9
        };
        const unitMap = {
            "拾": 10, "佰": 100, "仟": 1000,
            "万": 10000, "亿": 100000000
        };

        let result = 0;
        let temp = 0;
        let isNegative = false;

        // 处理负数
        if (chinese.startsWith("负")) {
            isNegative = true;
            chinese = chinese.substring(1);
        }

        for (let i = 0; i < chinese.length; i++) {
            const char = chinese[i];
            if (digitMap[char] !== undefined) {
                temp = digitMap[char];
            } else if (unitMap[char]) {
                if (temp === 0 && char === "拾") {
                    temp = 1;
                }
                result += temp * unitMap[char];
                temp = 0;
            } else if (char === "元") {
                result += temp;
                temp = 0;
            } else if (char === "角") {
                result += temp * 0.1;
                temp = 0;
            } else if (char === "分") {
                result += temp * 0.01;
                temp = 0;
            } else if (char !== "整") {
                throw new Error(`无效的字符: ${char}`);
            }
        }

        return isNegative ? -result : result;
    }
}

 

posted @ 2019-04-09 16:17  苗士军  阅读(235)  评论(0)    收藏  举报