How to avoid scientific notation for large numbers in JavaScript?

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

    Currently there is no native function to dissolve scientific notation. However, for this purpose you must write your own functionality.

    Here is my:

    function dissolveExponentialNotation(number)
    {
        if(!Number.isFinite(number)) { return undefined; }
    
        let text = number.toString();
        let items = text.split('e');
    
        if(items.length == 1) { return text; }
    
        let significandText = items[0];
        let exponent = parseInt(items[1]);
    
        let characters = Array.from(significandText);
        let minus = characters[0] == '-';
        if(minus) { characters.splice(0, 1); }
        let indexDot = characters.reduce((accumulator, character, index) =>
        {
            if(!accumulator.found) { if(character == '.') { accumulator.found = true; } else { accumulator.index++; } }
            return accumulator;
        }, { index: 0, found: false }).index;
    
        characters.splice(indexDot, 1);
    
        indexDot += exponent;
    
        if(indexDot >= 0 && indexDot < characters.length - 1)
        {
            characters.splice(indexDot, 0, '.');
        }
        else if(indexDot < 0)
        {
            characters.unshift("0.", "0".repeat(-indexDot));
        }
        else
        {
            characters.push("0".repeat(indexDot - characters.length));
        }
    
        return (minus ? "-" : "") + characters.join("");
    }
    

提交回复
热议问题