#100 把数字转换成中文


  • 0
    administrators

    完成将 toChineseNum, 可以将数字转换成中文大写的表示,处理到万级别,例如 toChineseNum(12345),返回 一万二千三百四十五


  • 1

    const toChineseNum = (num) => {
    if (num === 0) {
    return '零';
    }
    const bit = ['', '十', '百', '千'];
    const unit = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    const section = ['', '万'];
    let sectionPos = 0;
    let resultStr = '';
    let piece, needZero = false;

    function toCNum(n) {
        let bitPos = 0, rs = '', zeroNum = 0;
        while (n > 0) {
            let curNum = n % 10;
            if (curNum === 0) {
                zeroNum++;
                bitPos++;
            } else {
                if (bitPos === zeroNum)
                    zeroNum = 0;
                else if (zeroNum > 0) {
                    rs = '零' + rs;
                    zeroNum = 0;
                }
                rs = unit[curNum] + bit[bitPos++] + rs;
            }
            n = Math.floor(n / 10);
        }
        return rs;
    }
    
    while (num > 0) {
        piece = num % 10000;
        resultStr = toCNum(piece) + section[sectionPos] + (needZero ? '零' : '') + resultStr;
        needZero = piece < 1000 && piece > 0;
        sectionPos++;
        num = Math.floor(num / 10000);
    }
    return resultStr;
    

    }
    通过测试,不知道还有没有其他解法


  • 1

    好乱

    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 keys = ['零','一','二','三','四','五','六','七','八','九']
      var count = ['','十','百','千']
      var str ='';
      var nums = num.toString().split('').reverse();
      nums.map(function (a, index) {
          str = (keys[a]+ ( a==0?'': count[index>3 ? index-4 : index]))+(index=='4'?'万':'')+str 
      })
      return str.replace(/(零(?=零))|(零$)|(零(?=万))/g,'')
    }

  • 0

    只能8位以下的数啊


  • 0

    const toChineseNum = (num) => {
    // 按4位一段拆分
    let mulArr = ['', '十', '百', '千'];
    let index = 0;
    let cgArr = ['', '万'];
    let numArr = ['零', '一', '二', '三','四','五','六','七','八','九'];
    let str = num.toString();
    let res = '';
    for(let i=str.length - 1 ; i > -1; i--){
    let num = numArr[str[i]];
    let j = (str.length - i -1)%4;
    let unit = '';
    if(j == 0){
    unit = cgArr[index];
    index ++;
    } else {
    unit = mulArr[j];
    }
    res = num + unit + res;
    }
    return res.replace(/零[零十百千]+/g, '零').replace(/零万/, '万').replace(/零+$/, '');
    }


  • 0

    @roverlong#100 把数字转换成中文 中说:

    const toChineseNum = (num) => {
    if (num === 0) {
    return '零';
    }
    const bit = ['', '十', '百', '千'];
    const unit = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    const section = ['', '万'];
    let sectionPos = 0;
    let resultStr = '';
    let piece, needZero = false;

    function toCNum(n) {
        let bitPos = 0, rs = '', zeroNum = 0;
        while (n > 0) {
            let curNum = n % 10;
            if (curNum === 0) {
                zeroNum++;
                bitPos++;
            } else {
                if (bitPos === zeroNum)
                    zeroNum = 0;
                else if (zeroNum > 0) {
                    rs = '零' + rs;
                    zeroNum = 0;
                }
                rs = unit[curNum] + bit[bitPos++] + rs;
            }
            n = Math.floor(n / 10);
        }
        return rs;
    }
    
    while (num > 0) {
        piece = num % 10000;
        resultStr = toCNum(piece) + section[sectionPos] + (needZero ? '零' : '') + resultStr;
        needZero = piece < 1000 && piece > 0;
        sectionPos++;
        num = Math.floor(num / 10000);
    }
    return resultStr;
    

    }
    通过测试,不知道还有没有其他解法


  • 0

    借鉴了@hello 的replace部分。
    const toChineseNum = (num) => {
    const c = ["零","一","二","三","四","五","六","七","八","九","十"];
    const a = ["","十","百","千","万","十","百","千"];
    var len = num.toString().length;
    return num.toString().split('').map((value,index)=>{
    //末尾是0
    if(index === len-1 && value=== "0"){
    return ''
    }
    return c[value] + a[len-1-index]
    }).join('').replace(/零[零十百千]+/g, '零').replace(/零万/, '万').replace(/零+$/, '');
    }


  • 0

    function toChineseNum (num) {
    const Model = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九" ];
    const Unit = ["", "十", "百", "千", "万"];

    var result = "";
    var unit = '';
    var number = ''
    for(var i =num.length-1 ; i>=0; i--) {
        unit = Unit[num.length-1-i];
        number = Model[num[i]];
        if(num[i] === '0') {
            continue;
        }
        if(num[i+1] === '0' ) {
            result = "零" + result;
        }
    
        result = number + unit + result  ;
    }
    if(result[result.length-1] == '零') {
        result = result.slice(0, result.length-1);
    }
    return result;
    

    }


  • -2

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


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

登录后回复
 

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