Search code examples
javascriptdecimalexponentialfloor

Using JavaScript, how do I use the .toExponential() function, but only using two decimal places (9.99e9, instead of 9.9999e9)


If I have a variable that is set to 2345, and I want to convert it to exponential, I simply do variableName.toExponential().replace(/e+?/, 'e'), which will give me 2.345e3. However, I want it to only return two decimal places there, because otherwise once I get to much larger numbers, like 183947122, I'll get a long decimal, 1.83947122e8. I want this to floor to 1.83e8, but I can't figure out where I would put variable.toFixed(2) in this code.


Solution

  • You can do it with a regular expression and replace (which you're already using to replace e+ with e):

    const str = variableName.toExponential().replace(/^(\d*\.\d{0,2})\d*e\+(\d+)$/, "$1e$2");
    

    That captures the whole number portion of the coefficient plus up to two fractional digits of it, ignores any others, and captures the full exponent; it replaces the match with $1$2 so you're left with just the up-to-two digits of the coefficient:

    function test(variableName) {
        const raw = variableName.toExponential();
        const str = raw.replace(/^(\d*(?:\.\d{0,2})?)\d*e\+(\d+)$/, "$1e$2");
        console.log(variableName, "=>", raw, "=>", str);
    }
    
    test(2345);
    test(100);
    test(1019);
    test(183947122);