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;
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值