Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I noticed that these evaluate to true:

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

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

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading