#100 把数字转换成中文


  • -3

    @李莉的白白 想说宝宝的代码结果没有错,系统缺一直报错,呜呜~~


  • 0

    const toChineseNum = (num) => {
    const len = num.length;
    const strArr = ['万', '千', '百', '十', '']; // '万', '千', '百', '十', '' '万', '千', '百', '十', ''
    const toChinese = { 1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六', 7: '七', 8: '八', 9: '九', 0: '零' };
    let newStrArr = len > 5 ? strArr.slice(0, 4).concat(strArr).slice(-len) : strArr.slice(-len);
    let str = '';
    Array.from(num, (item, index) => {
    str = str + toChinese[item] + newStrArr[index];
    });
    return str;
    }
    测试可以 但是就是不通过,真不知道是为啥了


  • -1

    // 万亿
    const CHINA_NUM = '零一二三四五六七八九'
    const UNIT = '十百千万十百千亿十百千万'
    
    function numToChina (num) {
    	const slice = `${num}`.split('').reverse()
    
    	return slice.map((o, i) => {
    		return `${CHINA_NUM[o]}${+o ? UNIT[i - 1] || '' : ''}`
    	}).reverse().join('')
    }
    
    console.log(numToChina(process.argv[2]))
    

    秀编辑器


  • 0

    const toChineseNum = (num) => {
      if(typeof num != 'number') return false;
      if( !/^[1-9][0-9]{0,7}$/.test(num) && num != 0 ) return false;
      const map = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
      const map2 = ['', '十', '百', '千'];
      
      let s = (num + '').split('');
      let ss = [];
      let x = Math.ceil(s.length/4); 
      while(x--) {
        ss.unshift(s.splice(-4, 4));
      }
      
      ss = ss.map(_=>{
        const l = _.length; 
        return _.map( (d,i)=>{
          const a = map[d];
          const b = map2[l-i-1];
          return a == '零' ? a :`${a}${b}`;
        } ).join('').replace(/^(.*?)(零*)$/, '$1').replace(/零{2,}/g, '零');
      })
    
      return ss.join('万');
    }
    

  • 2

    function toChineseNum (num) {
    const model = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九" ];
    const unit = ["", "十", "百", "千", "万","十","百","千"];
    if(typeof num == "number"){
    num = num.toString();
    }
    var len = num.length;
    var numArray = num.split("");
    numArray.reverse();
    let sArray = [];
    numArray.map((n,index)=>{
    sArray.push(model[n]+""+unit[index]);
    });
    return sArray.reverse().join("");

    }

    零的情况还未处理。这样写应该简洁一些


  • 0

    let numName = {
    0: '零',
    1: '一',
    2: '二',
    3: '三',
    4: '四',
    5: '五',
    6: '六',
    7: '七',
    8: '八',
    9: '九'
    }
    let digit = {
    1: '十',
    2: '百',
    3: '千',
    4: '万',
    5: '亿'
    }
    const toChineseNum = (num) => {
    // TODO 一千八百五十六亿八千零二十万四千六百三十二 1856 8020 4632
    let strNum = num.toString().split("").reverse().join("");
    let arrNum = [];
    let result = '';
    if (strNum && strNum.length > 0) {
    for (let i = 0; i < strNum.length; i++) {
    let remain = (i + 1) % 4;
    if (remain == 0) {
    arrNum.push(strNum.slice(i - 3, i + 1));
    } else {
    if (i == strNum.length - 1) {
    arrNum.push(strNum.slice(i + 1 - remain, i + 1));
    }
    }
    }
    console.log(arrNum);
    for (let j = 0; j < arrNum.length; j++) {
    let group = arrNum[j];
    let res = '';
    for (let m = 0; m < group.length; m++) {
    if (digit[m] && group[m] != '0') {
    res = numName[group[m]] + digit[m] + res;
    } else {
    if (group[m] == '0' && (m == 0 || group[m-1] == '0')) {
    } else {
    res = numName[group[m]] + res;
    }
    }
    }
    if (j > 0) {
    result = res + digit[j + 3] + result;
    } else {
    result = res + result;
    }
    console.log(res);
    }
    }
    return result;
    }


  • 0

    0_1516678146823_upload-8c5680e4-87c3-4de5-8984-e27b38034be1

    呵呵。


  • 1

    const toChineseNum = (num) => {
    let str = '零一二三四五六七八九',
        str2 = ['', '十', '百', '千'];
    let Clu = Array.from( [...num.toString()].reverse(),
    	(v, i) => str[v] + (i == 4 ? '万' : (v == 0 ? '' : str2[i % 4]))).reverse().join('')
    	.replace(/零+/g, '零')
    	.replace(/(零+$)/, '')
    	.replace(/零+(?=万)/, '');
    return  Clu;
    }

  • 0

    希望能有更简便和清晰地逻辑处理
    const toChineseNum = (num) => {
    // TODO
    const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']; //changeNum[0] = "零"
    const unit = ["", "十", "百", "千", "万"]; //用于单位
    const getWan = (temp) => {
    let strArr = temp.toString().split("").reverse();
    let newNum = "";
    for (var i = 0; i < strArr.length; i++) {
    newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
    }
    return newNum;
    }
    // 若是十几上百万的,题目好坑,说万级别的,以为99999这样最大了;
    if (num.toString().length > 5) {
    let overWan = Math.floor(num / 10000);
    let noWan = num % 10000;
    // 千位为0的时候 余数会把0去掉;需要加上
    if (noWan.toString().length < 4) noWan = "0" + noWan;
    return getWan(overWan) + "万" + getWan(noWan)
    } else {
    return getWan(num);
    }

        }

  • 0

    const toChineseNum = (num) => {
      // TODO
      var numStr = num + ''
      var length = numStr.length
      if(length <= 4) {
        return read4Num(numStr, 0)
      } else {
        var preNum = numStr.substring(0, length - 4)
        var lastNum = numStr.substring(length - 4, length)
        return read4Num(preNum, 0) + '万' + read4Num(lastNum, 1)
      }
    }
    
    
    const read4Num = (numStr, type) => {
      var nums = ['零','一','二','三','四','五','六','七','八','九']
      var tags = ['', '十', '百', '千']
      var strLen = numStr.length
      var result = ''
      for(var index = 0; index < strLen; index++) {
        if(numStr[index] == '0') {
          if(result[result.length - 1] != ' ') {
            result += ' '
          }
        } else {
          result += nums[parseInt(numStr[index])] + tags[strLen - index - 1]
        }
      }
      if(type == 0) {
        result = result.trim()
      } else {
        if(result[result.length - 1] == ' ') {
          result = result.substring(0, result.length - 1)
        }
      }
      result = result.replace(/\s/g, '零')
      return result
    }
    

  • 0

    const toChineseNum = (num) => {
      const unit = ['', '十', '百', '千']
      const counts = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
    
      const pre = Math.floor(num / 10000)
      const next = num % 10000
    
      let getfour = (mynum, flag = false) => {
            if(!mynum){return ''}
      	let i = 0, str = ''
      	
      	while(flag ? i < 4 : mynum > 0 ) {
      		count = mynum % 10
      		mynum = Math.floor(mynum / 10)
      		str = (count ? counts[count] + unit[i] : str[0] == '零' ? '' : str.length && i ? '零' : '') + str
      		i++
      	}
      	return str
      }
      
      return pre ? getfour(pre) + '万' + getfour(next, true) : getfour(num)
    }
    

  • 0

    又来一个蠢解法

    const toChineseNum = (num) => {
      const pixel = ['', '十', '百', '千', '万'];
      const zhNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
      const arr = `${num}`.split('').reverse().map(n => +n);
      const res = arr.map((item, index) => {
        index = index >= pixel.length ? index % (pixel.length - 1) : index % pixel.length;
        if (item === 0) {
          return index === pixel.length - 1 ? pixel[index] : zhNums[item];
        } else {
          return zhNums[item]+pixel[index]
        }
      }).reverse().join('').replace(/零+/g, '零').replace(/^零|零$/, '').replace(/零([十百千万])/, ($0, $1) => $1)
      return res;
    }
    

  • 0

    function toChineseNum(number) {
    	const bit = [ '', '十', '百', '千' ];
    	const unit = [ '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' ];
    	return number
    		.toString()
    		.replace(/(\d)(?=(\d{4})+$)/g, '$1,')
    		.split(',')
    		.map((space) => {
    			let spaceResult = space
    				.split('')
    				.reverse()
    				.map((num, ii) => {
    					let chinabit = +num === 0 ? '' : bit[ii];
    					return unit[num] + chinabit;
    				})
    				.reverse()
    				.join('');
    			return spaceResult.replace(/零+/, '零').replace(/零*$/, '');
    		})
    		.join('万');
    }
    
    

    这样是不是方便以后扩展


  • 0

    var num = [零,一,二,三,四,五,六,七,八,九]
    var unit = ["",十,百,千,万]
    var a = 12345
    const result=a.split('').reserr.reverse().map((i,index)=>{
    return num[i]+unit[index]
    }).reverse()


  • 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);
    }
    

    搞到头痛


登录后回复
 

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