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

前端 未结 16 2178
名媛妹妹
名媛妹妹 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 22:57

    Use as a Number Prototype

    For easy and direct you. Simply make a prototype of it. Here is an example.

    Number.prototype.abbr = function (decimal = 2): string {
      const notations = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'],
        i = Math.floor(Math.log(this) / Math.log(1000));
      return `${parseFloat((this / Math.pow(1000, i)).toFixed(decimal))}${notations[i]}`;
    };
    

提交回复
热议问题