Why is (1 + Number.MIN_VALUE) equal to 1?

Advertisements

I noticed that these evaluate to true:

  • (1 + Number.MIN_VALUE) === 1

  • Object.is(1 + Number.MIN_VALUE, 1)

From the documentation:

The Number.MIN_VALUE static data property represents the smallest positive numeric value representable in JavaScript.

My questions are:

  1. Since Number.MIN_VALUE is nonzero, why does adding it to a given number not result in a different number?

  2. What is the minimum value that can be added to a given number to result in a different number?

>Solution :

For your questions:

For exact comparisons, due to the nature of internal floating point representation, you need to compare like this:

const x = 0.1, y = 0.2, expectedResult = 0.3;

function equalNumber(a,b) {
  return (a - b) < Number.EPSILON;
}

console.log('===', x + y === expectedResult);

console.log('equalNumber', equalNumber((x+y), expectedResult));

For your second question, that number you’re asking for is Number.EPSILON.

Leave a ReplyCancel reply