Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 551
shangxinbo Avatar asked May 18 '26 05:05

shangxinbo


2 Answers

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));
like image 113
Mistalis Avatar answered May 20 '26 17:05

Mistalis


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

like image 42
Damiano Avatar answered May 20 '26 17:05

Damiano