javascriptnumbers

How to compare two big number in javascript


Why below code output result is equal? How to compare?

var num1 = 340282000000000000000000000000000000001
var num2 = 340282000000000000000000000000000000000  // 3.402823E+38
if(num1 == num2) {
    console.log('num1 equal to num2');
} else if(num1 > num2) {
    console.log('num1 bigger than num2');
} else {
    console.log('num1 lower than num2')
}

Solution

  • Note that exponential notation is not meant for precision, it's an imprecise number, most of the time.

    Both numbers provided result in the same exponential number.

    It's possible to convert a big number to big integer just adding the suffix n:

    // NOTE THAT ALL NUMBERS ARE INTEGER
    
    let num1 = 340282000000000000000000000000000000001;
    let num2 = 340282000000000000000000000000000000000;
    let num3 = 340282000000000000000000000000000000001n;
    let num4 = 340282000000000000000000000000000000000n;
    let numC = BigInt(3.40282e+38);
    
    console.log('num1 =', String(num1));
    console.log('num2 =', String(num2));
    console.log('num3 =', String(num3));
    console.log('num4 =', String(num4));
    console.log('numC = 3.40282e+38 =', String(numC));
    
    console.log('num1 == num2?', num1 == num2);
    console.log('num3 == num4?', num3 == num4);