JavaScript中文与阿拉伯数字互相转换

JavaScript中文与阿拉伯数字互相转换

阿拉伯数字转中文

function numberToChinese(num) {
    
    
		let chnNumChar = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
		let chnUnitSection = ["", "万", "亿", "万亿", "亿亿"];
		let chnUnitChar = ["", "十", "百", "千"];
		function sectionToChinese(section) {
    
    
			let strIns = '',
				chnStr = '';
			let unitPos = 0;
			let zero = true;
			while (section > 0) {
    
    
				let v = section % 10;
				if (v === 0) {
    
    
					if (!zero) {
    
    
						zero = true;
						chnStr = chnNumChar[v] + chnStr;
					}
				} else {
    
    
					zero = false;
					strIns = chnNumChar[v];
					strIns += chnUnitChar[unitPos];
					chnStr = strIns + chnStr;
				}
				unitPos++;
				section = Math.floor(section / 10);
			}
			return chnStr;
		}
		let unitPos = 0;
		let strIns = '',
			chnStr = '';
		let needZero = false;
		if (num === 0) {
    
    
			return chnNumChar[0];
		}
		while (num > 0) {
    
    
			let section = num % 10000;
			if (needZero) {
    
    
				chnStr = chnNumChar[0] + chnStr;
			}
			strIns = sectionToChinese(section);
			strIns += (section !== 0) ? chnUnitSection[unitPos] : chnUnitSection[0];
			chnStr = strIns + chnStr;
			needZero = (section < 1000) && (section > 0);
			num = Math.floor(num / 10000);
			unitPos++;
		}
		return chnStr;
	}

中文转阿拉伯数字

function ChineseToNumber(chnStr) {
    
    
	let chnNumChar = {
    
    
    	: 0,
    	: 1,
    	: 2,
    	: 2,
    	: 3,
    	: 4,
    	: 5,
    	: 6,
    	: 7,
    	: 8,
    	: 9
	};
	let chnNameValue = {
    
    
    	: {
    
     value: 10, secUnit: false },
    	: {
    
     value: 100, secUnit: false },
    	: {
    
     value: 1000, secUnit: false },
    	: {
    
     value: 10000, secUnit: true },
    	亿: {
    
     value: 100000000, secUnit: true }
	}
    let rtn = 0;
    let section = 0;
    let number = 0;
    let secUnit = false;
    let  str = chnStr.split('');

    for (let i = 0; i < str.length; i++) {
    
    
        let num = chnNumChar[str[i]];
        if (typeof num !== 'undefined') {
    
    
            number = num;
            if (i === str.length - 1) {
    
    
                section += number;
            }
        } else {
    
    
            let unit = chnNameValue[str[i]].value;
            secUnit = chnNameValue[str[i]].secUnit;
            if (secUnit) {
    
    
                section = (section + number) * unit;
                rtn += section;
                section = 0;
            } else {
    
    
                section += (number * unit);
            }
            number = 0;
        }
    }
    return rtn + section;
}

猜你喜欢

转载自blog.csdn.net/weixin_48888726/article/details/127774053