#100 把数字转换成中文


  • 0

    我写了133行 就因为用了switch casc :(


  • 0

    @hangw
    index>3 ? index-4 : index 是不是改成index%4比较好?


  • 0

    0_1519723683049_upload-f4fbf0e7-6ebe-42e0-b730-ce38c548ddb9


  • 0

    想了好久,最后对结果中零的处理还是用了替换方式,感觉这样处理相对简单点

    const toChineseNum = (num) => {
       const str1 = ["万", "千", "百", "十", ""],
           str2 = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
       var str = "",
           num = num.toString(),
           arr = [],
           isW = "";
    
       if (num.length > 4) {
           arr.push(num.substring(0, num.length - 4)),
               arr.push(num.substring(num.length - 4));
           isW = "万";
       } else {
           arr.push(num);
       }
    
       for (let j = 0; j < arr.length; j++) {
           let str3 = str1.slice(5 - arr[j].length);
           for (let i = 0; i < arr[j].length; i++) {
               if (arr[j][i] === "0") {
                   str += str2[arr[j][i]];
               } else {
                   str += str2[arr[j][i]] + str3[i];
               }
           }
           str = str + isW;
           isW = "";
       }
    
       return str.replace(/\零+\万/, "万").replace(/\零+/g, "零").replace(/\零*$/, "");
    }

  • 0

    看到贴子里的正则,默默献上膝盖。。。
    顺便处理了负数

    const toChineseNum = (num) => {
    	const chiPos = ["千", "百", "十", ""];
    	const chiNum = ["", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
    
    	if (num === 0) {
    		return "零";
    	}
    
    	let symbol = "";
    	if (num < 0) {
    		num = -num;
    		symbol = "-";
    	}
    
    	let result = "";
    	num = num + "";
    	let frontZeros = "0".repeat(chiPos.length - Math.floor(num.length % chiPos.length))//补足前导0
    	let arr = (frontZeros + num).split("").map((e) => +e);
    	
    	//find first non-zero digit
    	let i = 0;
    	while (arr[i] === 0) {
    		i++;
    	}
    
    	//开始处理数字
    	let hasZero = false;
    	while (i < arr.length) {
    		if (arr[i] !== 0) {
    			if (hasZero) {
    				result += "零";
    				hasZero = false;
    			}
    			result += chiNum[arr[i]] + chiPos[Math.floor(i % chiPos.length)];
    		} else {
    			// 每组末尾的0,不用兑现,设置为false
    			if (Math.floor(i % chiPos.length) === 3) {
    				hasZero = false;
    			} else {
    				hasZero = true;
    			}
    		}
    
    		//判断是否加上"万""
    		if (i < arr.length - chiPos.length
    			&& Math.floor(i % chiPos.length) === 3) {
    			result += "万";
    		}
    
    		i++;
    	}
    
    	return result;
    }
    

  • 0

     const toChineseNum = nums => {
      const quots = ['万', '亿'];
      const chars = ['零','一','二','三','四','五','六','七','八','九'];
      const units = ['十','百','千'];
      const minus = '负';
    
      const toChars = ( [ row, col ], num ) => {
        if (num === '0' && col === 0) return quots[row-1] || '';
        if (num === '0' && col !== 0) return '';
        return (chars[num] || '') + ((col===0 ? quots[row-1] : units[col-1]) || '');
      }
    
      const assembly = ( { text, zero }, { num, char } ) => ({
        text: ( num === '0' ? ( zero ? char : ( char || chars[0] ) ) : char ) + text,
        zero: num == '0' ? ( zero || true ) : false
      });
    
      const toChinese = numbers => (
        (numbers + '').split('').reverse()
          .map((num, i) => ({ num: num, char: toChars( [ Math.trunc(i/4), i%4 ], num ) }) )
          .reduce( assembly, { text: '', zero: true } ).text
      );
    
      return  toChinese(nums);
    }
    

    搞到头痛


  • 0

    @walker

    你测试的是不带零的,1203,你试下,你的十位是错的。这不是重点,传入的是个数字类型,数字类型能有length属性吗?起码也要转换成字符串吧


  • 0

    let wei = ['', '十', '百', '千'];
    let wei2 = ['', '万', '亿'];
    let ns = ['零', "一", '二', '三', '四', '五', '六', '七', '八', '九']
    let str = num+'';
    let tmpStr = '';
    for(let i =0;i<str.length;i++){
    tmpStr+=ns[str[i]*1]
    }
    let tmpArr = tmpStr.split('').reverse();
    for(let i =0;i<tmpArr.length;i++){
    tmpArr[i] = tmpArr[i]+ wei[i%4];
    if(i%4===0||i===tmpArr.length){
    tmpArr[i] = tmpArr[i]+wei2[Math.floor(i/4)]
    }
    }
    let retStr = tmpArr.reverse().join('');
    retStr = retStr
    .replace(/零十/gi,'零')
    .replace(/零百/gi,'零')
    .replace(/零千/gi,'零')
    .replace(/零{2,}/gi,'零')
    .replace(/零万/gi,'万')
    .replace(/零亿/gi,'亿')
    .replace(/零$/,'')
    return retStr


  • 0

    let wei = ['', '十', '百', '千'];
            let wei2 = ['', '万', '亿'];
            let ns = ['零', "一", '二', '三', '四', '五', '六', '七', '八', '九']
            let str = num+'';
            let tmpStr = '';
            for(let i =0;i<str.length;i++){
                tmpStr+=ns[str[i]*1]
            }
            let tmpArr = tmpStr.split('').reverse();
            for(let i =0;i<tmpArr.length;i++){
                tmpArr[i] = tmpArr[i]+ wei[i%4];
                if(i%4===0||i===tmpArr.length){
                    tmpArr[i] = tmpArr[i]+wei2[Math.floor(i/4)]
                }
            }
            let retStr = tmpArr.reverse().join('');
            retStr = retStr
                .replace(/零十/gi,'零')
                .replace(/零百/gi,'零')
                .replace(/零千/gi,'零')
                .replace(/零{2,}/gi,'零')
                .replace(/零万/gi,'万')
                .replace(/零亿/gi,'亿')
                .replace(/零$/,'')
            return retStr
    

  • 0

    const toChineseNum = (num) => {

    let unit = ['', '十', '百', '千', '万']
    let numArr = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
    let arrNum = num.toString().split("").reverse();
    let strArr = arrNum.map((v, i) => {
     if (i === 4 && parseInt(v) === 0) {
        return "万"
      }
      i = i > 4 ? i - 4 : i;
      return parseInt(v) === 0 ? numArr[v] : numArr[v] + unit[i - 0]
    })
    return strArr.reverse().join("").replace(/(零(?=零))|(零$)|(零(?=万))/g, '')
    

    }


  • 0

    has been deleted


  • 0

    @ScriptOJ

    const toChineseNum = (num) => {
      // TODO
      let arr = num.toString().split('').reverse(),
          newArr = [];
      let dic = ['零','一','二','三','四','五','六','七','八','九'],
          unit = ['','十','百','千','万','十','百','千'];
      arr.forEach((item,index) => {
        if(item == 0 ){
           if(index == 4)newArr.unshift('万');
           else if(index > 0 && newArr[0] != '零' && newArr[0] != '万'){
             newArr.length && newArr.unshift('零');
           }
        }
        else newArr.unshift(dic[item] + unit[index])
      })
      return newArr.join('')
    }
    

  • 0

    @李莉的白白 系统bug 贴图看看?


  • 0

    const toChineseNum = (num) => {
    let arr=["零","一","二","三","四","五","六","七","八","九"],
    arr2=["","十","百","千","万","十","百","千","万"];
    let string="";
    let arr1=(num+"").split("").reverse();
    arr1.map((str,index)=>{
    string+=(index===4?arr2[index]:((+str)?arr2[index]:""))+arr[str];
    });
    string=string.replace(/万零*/,"万").replace(/零{2,}/g,"零").replace(/^零/,"");
    let arr3=string.split("");
    return arr3.reverse().join("");
    }v


  • 0

    const smallUnits = ['', '十', '百', '千']
    const chineseChars = '零一二三四五六七八九'.split('')
    const bigUnits = ['', '万', '亿', '兆']
    
    const toChineseNum = (num) => {
      const str = String(num)
      const length = str.length
      let hadZero = false // 表示前面是否有0
      let resultArr = []
      for (let i = 0; i < length; ++i) {
        let n = Number(str[i])
    
        // 可能需要给上一批加上大单位
        let reverseIndex = length - i - 1
        if (reverseIndex % 4 === 3 && i > 0) {
          resultArr.push(bigUnits[(reverseIndex + 1) / 4])
          hadZero = false // 新一批开始,重置前面零的个数
        }
    
        if (n === 0) {  // 如果是0,则暂时不读这一位
          hadZero = true
          continue
        }
    
        // 如果前面有0,而当前位不是0,则先读0,再处理该位
        if (hadZero && n !== 0) {
          resultArr.push('零')
          hadZero = false
        }
    
        // 读当前位
        resultArr.push(chineseChars[n])
        resultArr.push(smallUnits[reverseIndex % 4])
      }
      return resultArr.join('')
    }
    

  • 0

    用了正则和三目来做

    toChineseNum = (num) => {
      // TODO
      let result = ''
      let numStr = num.toString()
      const numberArr = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
      const unitArr = ['', '十', '百', '千', '万']
      for (let i = 0; i < numStr.length; i++) {
        result = result + numberArr[numStr[i]] + (parseInt(numStr[i]) === 0 ? ((numStr.length - i - 1) === 4 ? '万' : '') : ((numStr.length - i - 1) === 4 ? '万' : unitArr[(numStr.length - i - 1) % 4]))
      }
      return result.length > 1 ? result.replace(/零+/g, '零').replace(/零$/, '').replace(/零万/, '万') : result
    }

  • 0

    一个简洁的思路

    const toChineseNum = (num) => {
      if (num === 0) { return '零' }
      const digits = ['', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
      const units = ['', '十', '百', '千', '万']
      return [...String(num)].reduceRight((r, d, i, n) => {
        if (d === '-') { return '负' + r }
        const iUnit = (n.length - i - 1) % 5 + ((n.length - i - 1) / 5 | 0) // 0,1,2,3,4,1,2,3,4.....
        return digits[d] + (
          d === '0'
          ? iUnit % 4 === 0 // 是否个位和万位为 0 
            ? units[iUnit] // 保留单位
            : n[i+1] !== '0' ? '零' : '' // 只显示一个`零``
          : units[iUnit]
        ) + r
      }, '')
    }
    

  • 0

    const toChineseNum = (num) => {
    var Num = ['十','百','千','万','十','百','千'];
    var numStr = ['零','一','二','三','四','五','六','七','八','九'];
    var index = String(num).length - 1;
    var str = '';
    while(index>0){
    var pow = Math.pow(10,index);
    var i = Math.floor(num/pow);
    if(i==0){
    str += Num[index-1]=='万' ? '万' : numStr[i] ;
    }else{
    str += numStr[i] + Num[index-1] ;
    }
    num = num%pow;
    if(!num) break;
    index--;
    }
    if(num!=0){
    str+=numStr[num];
    }
    str = str.replace(/零{2,}/g,'零');
    str = str.replace(/零*(?=万)/,'');

    return str;
    }


  • 0

    const toChineseNum = (num) => {
      const digit = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
      const unit = [['', '万', '亿'], ['', '十', '百', '千']];
      let s = ''
      for (let i = 0; i < unit[0].length && num > 0; i += 1) {
        let p = '';
        for (let j = 0; j < unit[1].length && num > 0; j += 1) {
          p = digit[num % 10] + unit[1][j] + p;
          num = Math.floor(num / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
      }
      return s.replace(/(零.)*零$/, '').replace(/(零.)+/g, '零')
    }
    
    

  • 0

    @ScriptOJ

    怎么回事呀?0_1542198702696_屏幕快照 2018-11-14 下午8.29.00.png


登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待