How to avoid scientific notation for large numbers in JavaScript?

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

    I tried working with the string form rather than the number and this seemed to work. I have only tested this on Chrome but it should be universal:

    function removeExponent(s) {
        var ie = s.indexOf('e');
        if (ie != -1) {
            if (s.charAt(ie + 1) == '-') {
                // negative exponent, prepend with .0s
                var n = s.substr(ie + 2).match(/[0-9]+/);
                s = s.substr(2, ie - 2); // remove the leading '0.' and exponent chars
                for (var i = 0; i < n; i++) {
                    s = '0' + s;
                }
                s = '.' + s;
            } else {
                // positive exponent, postpend with 0s
                var n = s.substr(ie + 1).match(/[0-9]+/);
                s = s.substr(0, ie); // strip off exponent chars            
                for (var i = 0; i < n; i++) {
                    s += '0';
                }       
            }
        }
        return s;
    }
    

提交回复
热议问题