How to avoid scientific notation for large numbers in JavaScript?

后端 未结 22 2006
無奈伤痛
無奈伤痛 2020-11-22 00:31

JavaScript converts a large INT to scientific notation when the number becomes large. How can I prevent this from happening?

22条回答
  •  囚心锁ツ
    2020-11-22 00:50

    Here is my short variant of Number.prototype.toFixed method that works with any number:

    Number.prototype.toFixedSpecial = function(n) {
      var str = this.toFixed(n);
      if (str.indexOf('e+') === -1)
        return str;
    
      // if number is in scientific notation, pick (b)ase and (p)ower
      str = str.replace('.', '').split('e+').reduce(function(p, b) {
        return p + Array(b - p.length + 2).join(0);
      });
      
      if (n > 0)
        str += '.' + Array(n + 1).join(0);
      
      return str;
    };
    
    console.log( 1e21.toFixedSpecial(2) );       // "1000000000000000000000.00"
    console.log( 2.1e24.toFixedSpecial(0) );     // "2100000000000000000000000"
    console.log( 1234567..toFixedSpecial(1) );   // "1234567.0"
    console.log( 1234567.89.toFixedSpecial(3) ); // "1234567.890"

提交回复
热议问题