How to avoid scientific notation for large numbers in JavaScript?

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

    The following solution bypasses the automatic exponentional formatting for very big and very small numbers. This is outis's solution with a bugfix: It was not working for very small negative numbers.

    function numberToString(num)
    {
        let numStr = String(num);
    
        if (Math.abs(num) < 1.0)
        {
            let e = parseInt(num.toString().split('e-')[1]);
            if (e)
            {
                let negative = num < 0;
                if (negative) num *= -1
                num *= Math.pow(10, e - 1);
                numStr = '0.' + (new Array(e)).join('0') + num.toString().substring(2);
                if (negative) numStr = "-" + numStr;
            }
        }
        else
        {
            let e = parseInt(num.toString().split('+')[1]);
            if (e > 20)
            {
                e -= 20;
                num /= Math.pow(10, e);
                numStr = num.toString() + (new Array(e + 1)).join('0');
            }
        }
    
        return numStr;
    }
    
    // testing ...
    console.log(numberToString(+0.0000000000000000001));
    console.log(numberToString(-0.0000000000000000001));
    console.log(numberToString(+314564649798762418795));
    console.log(numberToString(-314564649798762418795));

提交回复
热议问题