How to avoid scientific notation for large numbers in JavaScript?

后端 未结 22 2022
無奈伤痛
無奈伤痛 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 01:02

    Busting out the regular expressions. This has no precision issues and is not a lot of code.

    function toPlainString(num) {
      return (''+ +num).replace(/(-?)(\d*)\.?(\d+)e([+-]\d+)/,
        function(a,b,c,d,e) {
          return e < 0
            ? b + '0.' + Array(1-e-c.length).join(0) + c + d
            : b + c + d + Array(e-d.length+1).join(0);
        });
    }
    
    console.log(toPlainString(12345e+12));
    console.log(toPlainString(12345e+24));
    console.log(toPlainString(-12345e+24));
    console.log(toPlainString(12345e-12));
    console.log(toPlainString(123e-12));
    console.log(toPlainString(-123e-12));
    console.log(toPlainString(-123.45e-56));
    console.log(toPlainString('1e-8'));
    console.log(toPlainString('1.0e-8'));

提交回复
热议问题