How to avoid scientific notation for large numbers in JavaScript?

后端 未结 22 2072
無奈伤痛
無奈伤痛 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:49

    This is what I ended up using to take the value from an input, expanding numbers less than 17digits and converting Exponential numbers to x10y

    // e.g.
    //  niceNumber("1.24e+4")   becomes 
    // 1.24x10 to the power of 4 [displayed in Superscript]
    
    function niceNumber(num) {
      try{
            var sOut = num.toString();
          if ( sOut.length >=17 || sOut.indexOf("e") > 0){
          sOut=parseFloat(num).toPrecision(5)+"";
          sOut = sOut.replace("e","x10")+"";
          }
          return sOut;
    
      }
      catch ( e) {
          return num;
      }
    }
    

提交回复
热议问题