shangxinbo
shangxinbo

Reputation: 964

Inconsistent addition with `Number.MAX_VALUE`

In Javascript, Number.MAX_VALUE is the biggest value for a number. I got a question that

(Number.MAX_VALUE + 123) == Number.MAX_VALUE  //true
(Number.MAX_VALUE + Number.MAX_VALUE) == Number.MAX_VALUE  //false

I can't understand. Can someone explain me?

Upvotes: 3

Views: 308

Answers (2)

Mistalis
Mistalis

Reputation: 18289

In the first example, you just increase your number by a really tiny number: 123 according to 1.79^308 is nothing. So you "lost" some precision: it does not change the number.

In the second one, you exceed the max value, so your number is not a number anymore, it is Infinity.

console.log(Number.MAX_VALUE + 123);
console.log(Number.MAX_VALUE + Number.MAX_VALUE);

/* Is (Number.MAX_VALUE + Number.MAX_VALUE) a number? */
console.log(Number.isInteger(Number.MAX_VALUE + Number.MAX_VALUE));

Upvotes: 5

Damiano
Damiano

Reputation: 811

In the first case you are just losing precision (adding a relatively tiny number to another has no effect), while in the second you are overflowing to Infinity.

Edit: Think of Number.MAX_VALUE+123 as an approximation: it's like trying to sum 1 + 0.000000000000000000000001.... you still get 1 because numbers only have a finite precision

Upvotes: 2

Related Questions