Convert long number into abbreviated string in JavaScript, with a special shortness requirement

前端 未结 16 2468
名媛妹妹
名媛妹妹 2020-11-30 22:33

In JavaScript, how would one write a function that converts a given [edit: positive integer] number (below 100 billion) into a 3-letter abbreviation -- where 0-9 an

16条回答
  •  不思量自难忘°
    2020-11-30 23:02

    This handles very large values as well and is a bit more succinct and efficient.

    abbreviate_number = function(num, fixed) {
      if (num === null) { return null; } // terminate early
      if (num === 0) { return '0'; } // terminate early
      fixed = (!fixed || fixed < 0) ? 0 : fixed; // number of decimal places to show
      var b = (num).toPrecision(2).split("e"), // get power
          k = b.length === 1 ? 0 : Math.floor(Math.min(b[1].slice(1), 14) / 3), // floor at decimals, ceiling at trillions
          c = k < 1 ? num.toFixed(0 + fixed) : (num / Math.pow(10, k * 3) ).toFixed(1 + fixed), // divide by power
          d = c < 0 ? c : Math.abs(c), // enforce -0 is 0
          e = d + ['', 'K', 'M', 'B', 'T'][k]; // append power
      return e;
    }
    

    Results:

    for(var a='', i=0; i < 14; i++){ 
        a += i; 
        console.log(a, abbreviate_number(parseInt(a),0)); 
        console.log(-a, abbreviate_number(parseInt(-a),0)); 
    }
    
    0 0
    -0 0
    01 1
    -1 -1
    012 12
    -12 -12
    0123 123
    -123 -123
    01234 1.2K
    -1234 -1.2K
    012345 12.3K
    -12345 -12.3K
    0123456 123.5K
    -123456 -123.5K
    01234567 1.2M
    -1234567 -1.2M
    012345678 12.3M
    -12345678 -12.3M
    0123456789 123.5M
    -123456789 -123.5M
    012345678910 12.3B
    -12345678910 -12.3B
    01234567891011 1.2T
    -1234567891011 -1.2T
    0123456789101112 123.5T
    -123456789101112 -123.5T
    012345678910111213 12345.7T
    -12345678910111212 -12345.7T
    

提交回复
热议问题