【问题标题】:Is there any way to shorten a number with js? [duplicate]有没有办法用js缩短数字? [复制]
【发布时间】:2020-12-03 11:35:13
【问题描述】:

有什么办法可以缩短数字吗?例如像 1.000.000 到 1M,1.000 到 1k,10.000 到 10k,等等

【问题讨论】:

标签: javascript numbers


【解决方案1】:

如果你使用的是js库或框架(如angular、react),可以使用这个

number-abbreviate

【讨论】:

    【解决方案2】:

    试试这样的:

    函数 fnum(x) { if(isNaN(x)) 返回 x;

    if(x < 9999) {
        return x;
    }
    
    if(x < 1000000) {
        return Math.round(x/1000) + "K";
    }
    if( x < 10000000) {
        return (x/1000000).toFixed(2) + "M";
    }
    
    if(x < 1000000000) {
        return Math.round((x/1000000)) + "M";
    }
    
    if(x < 1000000000000) {
        return Math.round((x/1000000000)) + "B";
    }
    
    return "1T+";
    

    }

    【讨论】:

      【解决方案3】:

      你可以试试这样的:

      function shortenNum(num, decimalDigits) {
        if (isNaN(num)) {
          console.log(`${num} is not a number`)
          return false;
        }
      
        const magnitudes = {
          none: 1,
          k: 1000,
          M: 1000000,
          G: 1000000000,
          T: 1000000000000,
          P: 1000000000000000,
          E: 1000000000000000000,
          Z: 1000000000000000000000,
          Y: 1000000000000000000000000
        };
      
        const suffix = String(Math.abs(num)).length <= 3 ?
          'none' :
          Object.keys(magnitudes)[Math.floor(String(Math.abs(num)).length / 3)];
      
        let shortenedNum
        if (decimalDigits && !isNaN(decimalDigits)) {
          const forRounding = Math.pow(10, decimalDigits)
          shortenedNum = Math.round((num / magnitudes[suffix]) * forRounding) / forRounding
        } else {
          shortenedNum = num / magnitudes[suffix];
        }
      
        return String(shortenedNum) + (suffix !== 'none' && suffix || '');
      }
      
      // tests
      console.log('1:', shortenNum(1));
      console.log('12:', shortenNum(12));
      console.log('198:', shortenNum(198));
      console.log('1278:', shortenNum(1278));
      console.log('1348753:', shortenNum(1348753));
      console.log('7594119820:', shortenNum(7594119820));
      console.log('7594119820 (rounded to 3 decimals):', shortenNum(7594119820, 3));
      console.log('7594119820 (invalid rounding):', shortenNum(7594119820, 'foo'));
      console.log('153000000:', shortenNum(153000000));
      console.log('foo:', shortenNum('foo'));
      console.log('-15467:', shortenNum(-15467));
      console.log('0:', shortenNum(0));
      console.log('-0:', shortenNum(-0));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多