【较难】算法nodeJs:人民币转换

182 阅读2分钟

描述

考试题目和要点:

1、中文大写金额数字前应标明“人民币”字样。中文大写金额数字应用壹、贰、叁、肆、伍、陆、柒、捌、玖、拾、佰、仟、万、亿、元、角、分、零、整等字样填写。

2、中文大写金额数字到“元”为止的,在“元”之后,应写“整字,如532.00应写成“人民币伍佰叁拾贰元整”。在”角“和”分“后面不写”整字。

3、阿拉伯数字中间有“0”时,中文大写要写“零”字,阿拉伯数字中间连续有几个“0”时,中文大写金额中间只写一个“零”字,如6007.14,应写成“人民币陆仟零柒元壹角肆分“。

4、10应写作“拾”,100应写作“壹佰”。例如,1010.00应写作“人民币壹仟零拾元整”,110.00应写作“人民币壹佰拾元整”

5、十万以上的数字接千不用加“零”,例如,30105000.00应写作“人民币叁仟零拾万伍仟元整”

输入描述:

输入一个double数

输出描述:

输出人民币格式

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    while ((line = await readline())) {
        let [num1, num2] = line.split(".");
        const strs = num1
            .replace(/(?=(\d{4})+$)/g, ".") //这个正则表达式会在每四位数字之间插入一个点号(.)
            .split(".") //将字符串按照点号(.)进行分割,生成一个数组
            .filter(Boolean); // 过滤掉数组中的空字符串("")
        const chars = [
            "零",
            "壹",
            "贰",
            "叁",
            "肆",
            "伍",
            "陆",
            "柒",
            "捌",
            "玖",
        ];
        const unit = ["", "拾", "佰", "仟"];
        const bigUnit = ["", "万", "亿"];
        //转换4位以下的数字的方法
        function _tranform(numStr) {
            let result = "";
            for (let i = 0; i < numStr.length; i++) {
                const digit = +numStr[i];
                const c = chars[digit];
                const u = unit[numStr.length - i - 1];
                if (digit == 0) {
                    //如果当前位置上字符为‘0’
                    // 如果当前result末尾已经是零,则不拼接;不是'零',才可以拼接上这个零;
                    //保证中间有多个0时只读一个零,如3001;
                    if (result[result.length - 1] !== chars[0]) {
                        result += c; //而且为零的拼接时不要单位
                    }
                } else {
                    result += c + u;
                }
            }
            // 如果最后末尾还是零的话,说明是形如'3000'或'3010'这种,需要处理一下
            if (result[result.length - 1] === chars[0]) {
                result = result.slice(0, -1);
            }
            return result;
        }
        // console.log(_tranform('1090'))
        let result = "人民币";
        //处理整数部分 num1 -> strs
        for (let i = 0; i < strs.length; i++) {
            const part = strs[i];
            const c = _tranform(part);
            const u = c ? bigUnit[strs.length - i - 1] : "";
            result += c + u;
        }
        // console.log(result);
        if (result !== "人民币") {
            result = (result + "元").replace(/壹拾/g, "拾");
        }
        //处理小数部分 num2 角和分
        if (num2 == "00") {
            result += "整";
        } else {
            if (num2[0] !== "0") {
                result += chars[num2[0]] + "角";
            }
            if (num2[1] !== "0") {
                result += chars[num2[1]] + "分";
            }
        }
        console.log(result);
    }
})();