阿拉伯数字转中文数字(千亿以内,以上同理)

自己想的比较笨的办法:
  1. 检查下是否有负号,有的话先转为,然后将整数部分和小数部分提取出来。
  2. 整数部分从右至左按照每四个分组,每组都插入,然后处理零(首尾的零去掉,中间的多个零合并为一个)。
  3. 各分组之间插入亿,然后与小数部分以连接。
  4. 将以上得到结果中的数字统一转为中文。
function arab2Chinese(number) {
    if(isNaN(number)) return;
    var numberArr = [], tempStr = '', tempArr = (number + '').split('-');
    var getChineseNumber = function(numberStr) {
        var cNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
        var numberArr = numberStr.split(''), i, len;
        for(i = 0, len = numberArr.length; i < len; i += 1) {
            var curNum = numberArr[i];
            if(!isNaN(curNum)) numberArr[i] = cNums[Number(curNum)];
        }
        return numberArr.join('');
    }
    var transfer = function(numberStr) {
        var i, numberArr = [], len = numberStr.length, parts = Math.ceil(len / 4), remains = len % 4;
        if(parts < 2) {
            numberArr.push(addUnits(numberStr.substr(0, remains)));
        } else if(parts < 3) {
            numberArr.push(addUnits(numberStr.substr(0, remains)), '万', addUnits(numberStr.substr(3, 4)));
        } else {
            numberArr.push(addUnits(numberStr.substr(0, remains)), '亿', addUnits(numberStr.substr(3, 4)), '万', addUnits(numberStr.substr(7, 4)));
        }
        return numberArr.join('');
    }
    var addUnits = function(numberStr) {
        var i, len = numberStr.length;
        if(len === 2) {
            numberStr = numberStr.replace(/(\d)(\d)/,'$1十$2');
        } else if(len === 3) {
            numberStr = numberStr.replace(/(\d)(\d)(\d)/,'$1百$2十$3');
        } else if(len === 4) {
            numberStr = numberStr.replace(/(\d)(\d)(\d)(\d)/,'$1千$2百$3十$4');
        }
        return numberStr.replace(/^((0\D){1,3})(([1-9]\D){0,2}\d)$/, '$3').replace(/^(([1-9]\D){1,3}(0\D[1-9]\D){0,1})((0\D){0,3}0*$)/, '$1').replace(/^(([1-9]\D){1,2})(0\D){1,2}(\d)$/, '$10$4');
    }
    
    if(tempArr.length === 2) {
        numberArr.push('负');
        tempStr = tempArr[1];
    } else {
        tempStr = tempArr[0];
    }
    tempArr = tempStr.split('.');
    if(tempArr.length === 2) {
        numberArr.push(getChineseNumber(transfer(tempArr[0])), '点', getChineseNumber(tempArr[1]));
    } else {
        numberArr.push(getChineseNumber(transfer(tempArr[0])));
    }
    console.log(numberArr.join(''));

};
arab2Chinese(-20100300020.8802); //负二百零一亿三十万二十点八八零二
优化:

Thinking...

你可能感兴趣的:(阿拉伯数字转中文数字(千亿以内,以上同理))