javascriptprecision

How to get numbers toPrecision higher than 21 in javascript


How to get numbers toPrecision higher than 21 in javascript?

I am getting this number 8.426661309628124e+22

When it should be this 8.4266613096281243382112

When I use toPrecision(21) I get this 8.42666130962812428616e+22

// my result is a result of this calculation  
 var val=10;
 feb=[0,1];
 for(var i=2; i<=val; i++){
    feb[i]= feb[i-2] + Math.pow(feb[i-1],2);
    }    
    console.log(feb[val-1])


Solution

  • As the precision of JavaScript's internal representation of the "number" type (double-precision floating point) is limited, you'd need a Big Integer type that overcomes this limitation.

    There is the BigInt type:

    // Store the feb numbers as BigInts:
    const val = 10;
    const feb = [0n, 1n];
    for (let i = 2; i <= val; i++) {
        feb[i] = feb[i-2] + feb[i-1] * feb[i-1];
        console.log(feb[i].toString());
    }
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    Other languages also provide big integers out of the box, such as Python:

    val = 10
    feb = [0,1]
    for i in range(2, val+1):
        feb.append(feb[i-2] + feb[i-1] ** 2)
        print(feb[i])