skip to Main Content

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')
}

2

Answers


  1. Hi it seems like you hit the maximum value that Java can handle for an integer, for such high value, you can try :

    var num1 = BigInteger("340282000000000000000000000000000000001");

    var num2 = BigInteger("340282000000000000000000000000000000000");

    BigInteger class is used for the mathematical operation which involves very big integer calculations that are outside the limit of all available primitive data types.

    Login or Signup to reply.
  2. 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;
    
    console.log('num1 =', String(num1));
    console.log('num2 =', String(num2));
    console.log('num3 =', String(num3));
    console.log('num4 =', String(num4));
    
    console.log('num1 == num2?', num1 == num2);
    console.log('num3 == num4?', num3 == num4);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search